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 ProviderRole, 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
85#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
87pub struct ConsumerIdentity {
88 pub module_id: String,
89 pub launch_nonce: String,
90}
91
92impl std::fmt::Debug for ConsumerIdentity {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 f.debug_struct("ConsumerIdentity")
99 .field("module_id", &self.module_id)
100 .field(
101 "launch_nonce",
102 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
103 )
104 .finish()
105 }
106}
107
108pub mod ops {
119 pub const SERVER: &str = "server.";
120 pub const CATALOG: &str = "catalog.";
121 pub const ROUTE: &str = "route.";
122 pub const SUPERVISOR: &str = "supervisor.";
123 pub const CONFIG: &str = "config.";
124
125 pub const SERVER_DESCRIBE: &str = "server.describe";
126 pub const CATALOG_LIST: &str = "catalog.list";
127 pub const ROUTE_OPEN: &str = "route.open";
128 pub const ROUTE_POLL: &str = "route.poll";
129 pub const ROUTE_CLOSING: &str = "route.closing";
130 pub const ROUTE_CLOSED: &str = "route.closed";
131 pub const SUPERVISOR_LIST: &str = "supervisor.list";
132 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
133 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
134 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
135 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
136 pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
137 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
138 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
139 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
140 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
141 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
142 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
143 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
144 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
145 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
146 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
147 pub const ACTIVITY_RECORD: &str = "activity.record";
148 pub const ACTIVITY_QUERY: &str = "activity.query";
149 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
154#[serde(tag = "op")]
155#[allow(clippy::large_enum_variant)]
158pub enum ClientControlRequest {
159 #[serde(rename = "server.describe")]
160 ServerDescribe {},
161 #[serde(rename = "catalog.list")]
162 CatalogList {
163 #[serde(default)]
168 module_id: Option<String>,
169 },
170 #[serde(rename = "route.open")]
171 RouteOpen {
172 target: RouteTarget,
173 identity: BindIdentity,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
183 consumer_identity: Option<ConsumerIdentity>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
192 consumer_capabilities: Option<Vec<String>>,
193 #[serde(default, skip_serializing_if = "Option::is_none")]
204 role_versions: Option<BTreeMap<String, String>>,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
207 admission_facts: Option<serde_json::Value>,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
215 scope: Option<ScopeSelector>,
216 },
217 #[serde(rename = "route.poll")]
218 RoutePoll {
219 route_channel: u16,
220 route_epoch: u32,
221 kind: PollKind,
222 },
223 #[serde(rename = "supervisor.list")]
224 SupervisorList {},
225 #[serde(rename = "supervisor.spawn_snapshot")]
227 SupervisorSpawnSnapshot {},
228 #[serde(rename = "supervisor.spawn_subscribe")]
244 SupervisorSpawnSubscribe {
245 #[serde(default, skip_serializing_if = "Option::is_none")]
246 since: Option<SpawnCursor>,
247 },
248 #[serde(rename = "supervisor.restart")]
249 SupervisorRestart {
250 module_id: String,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
261 drain_timeout_ms: Option<u64>,
262 },
263 #[serde(rename = "supervisor.swap")]
278 SupervisorSwap {
279 module_id: String,
280 #[serde(default, skip_serializing_if = "Option::is_none")]
283 ready_timeout_ms: Option<u64>,
284 },
285 #[serde(rename = "supervisor.reload")]
286 SupervisorReload { module_id: String },
287 #[serde(rename = "supervisor.rescan")]
288 SupervisorRescan {
289 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
309 preview: bool,
310 },
311 #[serde(rename = "supervisor.rescan_checked")]
335 SupervisorRescanChecked {
336 preview: bool,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
338 candidate: Option<String>,
339 #[serde(default, skip_serializing_if = "Option::is_none")]
340 expect: Option<RescanExpect>,
341 },
342 #[serde(rename = "supervisor.release_reserved")]
346 SupervisorReleaseReserved { module_id: String },
347 #[serde(rename = "supervisor.set_enabled")]
348 SupervisorSetEnabled { module_id: String, enabled: bool },
349 #[serde(rename = "supervisor.health_probe")]
350 SupervisorHealthProbe { module_id: String },
351 #[serde(rename = "supervisor.health")]
352 SupervisorHealth {},
353 #[serde(rename = "supervisor.routes")]
366 SupervisorRoutes {
367 #[serde(default, skip_serializing_if = "Option::is_none")]
368 module_id: Option<String>,
369 },
370 #[serde(rename = "supervisor.provenance")]
373 SupervisorProvenance {
374 #[serde(default, skip_serializing_if = "Option::is_none")]
375 module_id: Option<String>,
376 },
377 #[serde(rename = "supervisor.stderr_tail")]
385 SupervisorStderrTail {
386 module_id: String,
387 #[serde(default, skip_serializing_if = "Option::is_none")]
388 max_lines: Option<u32>,
389 #[serde(default, skip_serializing_if = "Option::is_none")]
390 max_bytes: Option<u32>,
391 },
392 #[serde(rename = "supervisor.terminals")]
405 SupervisorTerminals { module_id: String },
406}
407
408#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
410#[serde(tag = "op")]
411pub enum ClientControlResponse {
412 #[serde(rename = "server.describe")]
413 ServerDescribe {
414 protocol_ver: u8,
415 subc_ops: Vec<String>,
416 capabilities: Vec<String>,
417 connected_clients: u64,
418 #[serde(default, skip_serializing_if = "Option::is_none")]
419 counters: Option<serde_json::Value>,
420 #[serde(default, skip_serializing_if = "Option::is_none")]
427 build_git_sha: Option<String>,
428 #[serde(default, skip_serializing_if = "Option::is_none")]
434 build_lock_digest: Option<String>,
435 #[serde(default, skip_serializing_if = "Vec::is_empty")]
439 capability_requirements: Vec<CapabilityRequirementStatus>,
440 #[serde(default, skip_serializing_if = "Option::is_none")]
445 machine_id: Option<String>,
446 #[serde(default, skip_serializing_if = "Option::is_none")]
455 config_path: Option<PathBuf>,
456 },
457 #[serde(rename = "catalog.list")]
458 CatalogList {
459 generation: u64,
460 modules: Vec<CatalogEntry>,
461 subc_ops: Vec<String>,
462 },
463 #[serde(rename = "route.open")]
464 RouteOpen {
465 route_channel: u16,
466 route_epoch: u32,
467 },
468 #[serde(rename = "route.poll")]
469 RoutePoll {
470 route_channel: u16,
471 route_epoch: u32,
472 status: Option<String>,
473 live: Option<bool>,
474 },
475 #[serde(rename = "supervisor.list")]
476 SupervisorList {
477 generation: u64,
478 modules: Vec<SupervisorEntry>,
479 },
480 #[serde(rename = "supervisor.spawn_snapshot")]
481 SupervisorSpawnSnapshot {
482 #[serde(flatten)]
483 snapshot: SpawnSnapshot,
484 },
485 #[serde(rename = "supervisor.ack")]
486 SupervisorAck { module_id: String, applied: bool },
487 #[serde(rename = "supervisor.rescan")]
488 SupervisorRescan {
489 #[serde(flatten)]
490 result: SupervisorRescanResult,
491 },
492 #[serde(rename = "supervisor.health_probe")]
493 SupervisorHealthProbe {
494 module_id: String,
495 status: HealthStatus,
496 #[serde(default, skip_serializing_if = "Option::is_none")]
497 detail: Option<String>,
498 #[serde(default, skip_serializing_if = "Option::is_none")]
499 metrics: Option<serde_json::Value>,
500 },
501 #[serde(rename = "supervisor.health")]
502 SupervisorHealth {
503 generation: u64,
504 modules: Vec<SupervisorHealthEntry>,
505 },
506 #[serde(rename = "supervisor.routes")]
507 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
508 #[serde(rename = "supervisor.provenance")]
509 SupervisorProvenance {
510 daemon: SupervisorDaemonProvenance,
511 modules: Vec<SupervisorModuleProvenance>,
512 },
513 #[serde(rename = "supervisor.stderr_tail")]
514 SupervisorStderrTail {
515 module_id: String,
516 #[serde(flatten)]
517 tail: StderrTail,
518 },
519 #[serde(rename = "supervisor.terminals")]
520 SupervisorTerminals {
521 module_id: String,
522 #[serde(flatten)]
523 terminals: TerminalHistory,
524 },
525}
526
527#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
532#[serde(tag = "op")]
533pub enum ClientControlPush {
534 #[serde(rename = "route.closing")]
535 RouteClosing {
536 module_id: String,
537 #[serde(default)]
540 channels: Vec<u16>,
541 reason: RouteCloseReason,
542 },
543 #[serde(rename = "route.closed")]
544 RouteClosed {
545 module_id: String,
546 #[serde(default)]
549 channels: Vec<u16>,
550 reason: RouteCloseReason,
551 drained: bool,
553 abandoned: u32,
556 #[serde(default)]
558 excluded_subscriptions: u32,
559 #[serde(default, skip_serializing_if = "Option::is_none")]
565 terminal: Option<bool>,
566 },
567}
568
569#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
571pub struct SpawnCursor {
572 pub daemon_incarnation: String,
573 pub seq: u64,
574}
575
576#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
578pub struct LiveSpawn {
579 pub module_id: String,
580 pub spawn_generation: u64,
581 pub pid: u32,
582 pub spawned_at_ms: u64,
583}
584
585#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
587pub struct SpawnSnapshot {
588 pub cursor: SpawnCursor,
589 pub ring_bound: u64,
591 pub live: Vec<LiveSpawn>,
592}
593
594#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
596#[serde(rename_all = "snake_case")]
597pub enum SpawnEventKind {
598 Spawned,
599 Exited,
600}
601
602#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
608pub struct SpawnEvent {
609 pub cursor: SpawnCursor,
610 pub kind: SpawnEventKind,
611 pub module_id: String,
612 pub spawn_generation: u64,
613 pub pid: u32,
614 #[serde(default, skip_serializing_if = "Option::is_none")]
615 pub exit_code: Option<i32>,
616 #[serde(default, skip_serializing_if = "Option::is_none")]
617 pub exit_signal: Option<i32>,
618}
619
620#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
622pub struct StderrTail {
623 pub capture: StderrCaptureState,
624 pub entries: Vec<StderrTailEntry>,
625 #[serde(default, skip_serializing_if = "is_zero_u64")]
634 pub dropped_lines: u64,
635}
636
637#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
639pub struct SupervisorRouteModule {
640 pub module_id: String,
641 pub routes: Vec<SupervisorRoute>,
642}
643
644#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
646pub struct SupervisorRoute {
647 pub consumer: SupervisorRouteConsumer,
648 pub age_ms: u64,
650 pub draining: bool,
653 #[serde(default, skip_serializing_if = "Option::is_none")]
659 pub drain_reason: Option<RouteCloseReason>,
660}
661
662#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
664pub struct SupervisorModuleProvenance {
665 pub module_id: String,
666 pub module_declared: ModuleDeclaredProvenance,
667 pub daemon_observed: SupervisorObservedProcess,
668}
669
670#[derive(Debug, Clone, PartialEq)]
672pub enum ModuleDeclaredProvenance {
673 Reported {
674 build: ManifestProvenance,
675 },
676 Unverifiable,
677 Unknown {
680 tag: String,
681 body: OrderedJsonObject,
682 },
683}
684
685#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
690pub struct SupervisorObservedProcess {
691 #[serde(default, skip_serializing_if = "Option::is_none")]
697 pub launch_nonce_source: Option<String>,
698 #[serde(default, skip_serializing_if = "Option::is_none")]
699 pub pid: Option<u32>,
700 #[serde(default, skip_serializing_if = "Option::is_none")]
701 pub spawned_at_ms: Option<u64>,
702 #[serde(default, skip_serializing_if = "Option::is_none")]
703 pub spawned_from: Option<PathBuf>,
704 pub running_image: RunningImageAgreement,
705}
706
707#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
710pub struct PendingReloadVerdict {
711 pub path: ReloadPathAgreement,
712 pub image: RunningImageAgreement,
713 #[serde(default, skip_serializing_if = "Option::is_none")]
714 pub spec: Option<LaunchSpecAgreement>,
715}
716
717#[cfg(test)]
718mod launch_spec_wire_tests {
719 use super::*;
720
721 #[test]
722 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
723 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
724 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
725 assert_eq!(parsed.spec, None);
726 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
727 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
728 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
729 assert!(
730 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
731 );
732 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
733 let unavailable = LaunchSpecAgreement::Unavailable {
734 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
735 };
736 let encoded = serde_json::to_string(&unavailable).unwrap();
737 assert_eq!(
738 encoded,
739 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
740 );
741 assert_eq!(
742 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
743 unavailable
744 );
745 }
746}
747
748#[derive(Debug, Clone, PartialEq)]
751pub enum LaunchSpecAgreement {
752 Match,
753 Mismatch,
754 Unavailable {
755 reason: LaunchSpecUnavailableReason,
756 },
757 Unknown {
758 tag: String,
759 body: OrderedJsonObject,
760 },
761}
762
763open_string_enum! {
764 LaunchSpecUnavailableReason {
765 NotRunning => "not_running",
766 SpawnedSpecUnavailable => "spawned_spec_unavailable",
767 }
768}
769
770#[derive(Debug, Clone, PartialEq)]
772pub enum ReloadPathAgreement {
773 Match,
774 Mismatch {
775 configured: PathBuf,
776 spawned_from: PathBuf,
777 },
778 Unavailable {
779 reason: ReloadPathUnavailableReason,
780 },
781 Unknown {
782 tag: String,
783 body: OrderedJsonObject,
784 },
785}
786
787open_string_enum! {
788 ReloadPathUnavailableReason {
790 NotRunning => "not_running",
791 SpawnedPathUnavailable => "spawned_path_unavailable",
792 }
793}
794
795#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
797pub struct SupervisorDaemonProvenance {
798 pub daemon_build: DaemonBuildProvenance,
799 pub daemon_observed: DaemonObservedProcess,
800}
801
802#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
804pub struct DaemonBuildProvenance {
805 #[serde(default, skip_serializing_if = "Option::is_none")]
806 pub build_git_sha: Option<String>,
807 #[serde(default, skip_serializing_if = "Option::is_none")]
808 pub build_lock_digest: Option<String>,
809}
810
811#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
813pub struct DaemonObservedProcess {
814 #[serde(default, skip_serializing_if = "Option::is_none")]
815 pub pid: Option<u32>,
816 #[serde(default, skip_serializing_if = "Option::is_none")]
821 pub started_at_ms: Option<u64>,
822 pub running_image: RunningImageAgreement,
823}
824
825#[derive(Debug, Clone, PartialEq)]
827pub enum RunningImageAgreement {
828 Match {
829 evidence: RunningImageEvidence,
830 },
831 Mismatch {
832 running: RunningImageEvidence,
833 disk: RunningImageEvidence,
834 },
835 Unavailable {
836 reason: RunningImageUnavailableReason,
837 },
838 Unknown {
841 tag: String,
842 body: OrderedJsonObject,
843 },
844}
845
846#[derive(Debug, Clone, PartialEq)]
848pub enum RunningImageEvidence {
849 LinuxProcSha256 {
850 digest: String,
851 },
852 MacosSpawnInode {
853 device: u64,
854 inode: u64,
855 },
856 WindowsSpawnFileId {
858 volume_serial_number: u64,
859 file_id: [u8; 16],
860 },
861 Unknown {
864 tag: String,
865 body: OrderedJsonObject,
866 },
867}
868
869open_string_enum! {
870 RunningImageUnavailableReason {
872 NotRunning => "not_running",
873 UnsupportedPlatform => "unsupported_platform",
874 RunningExecutableUnreadable => "running_executable_unreadable",
875 RunningExecutablePermissionDenied => "running_executable_permission_denied",
876 ProcessHidden => "process_hidden",
877 SpawnedPathUnreadable => "spawned_path_unreadable",
878 HashFailed => "hash_failed",
879 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
880 }
881}
882
883#[derive(Debug, Clone, PartialEq)]
889pub enum SupervisorRouteConsumer {
890 Reserved {
891 module_id: String,
892 },
893 Direct {
894 connection_id: u64,
895 },
896 Unknown {
899 tag: String,
900 body: OrderedJsonObject,
901 },
902}
903
904#[derive(Debug, Clone, PartialEq)]
911pub enum StderrCaptureState {
912 Captured,
915 Incomplete { reason: String },
917 NotCaptured { reason: String },
919 Unknown {
922 tag: String,
923 body: OrderedJsonObject,
924 },
925}
926
927#[derive(Debug, Clone, PartialEq)]
928pub enum StderrTailEntry {
929 Line {
930 text: String,
931 truncated: bool,
936 at_ms: Option<u64>,
940 },
941 ProcessStart,
946 Unknown {
949 tag: String,
950 body: OrderedJsonObject,
951 },
952}
953
954#[derive(Debug, Serialize, Deserialize)]
955#[serde(tag = "status", rename_all = "snake_case")]
956enum ModuleDeclaredProvenanceWire {
957 Reported { build: ManifestProvenance },
958 Unverifiable,
959}
960
961#[derive(Debug, Serialize, Deserialize)]
962#[serde(tag = "status", rename_all = "snake_case")]
963enum RunningImageAgreementWire {
964 Match {
965 evidence: RunningImageEvidence,
966 },
967 Mismatch {
968 running: RunningImageEvidence,
969 disk: RunningImageEvidence,
970 },
971 Unavailable {
972 reason: RunningImageUnavailableReason,
973 },
974}
975
976#[derive(Debug, Serialize, Deserialize)]
977#[serde(tag = "status", rename_all = "snake_case")]
978enum ReloadPathAgreementWire {
979 Match,
980 Mismatch {
981 configured: PathBuf,
982 spawned_from: PathBuf,
983 },
984 Unavailable {
985 reason: ReloadPathUnavailableReason,
986 },
987}
988
989#[derive(Debug, Serialize, Deserialize)]
990#[serde(tag = "status", rename_all = "snake_case")]
991enum LaunchSpecAgreementWire {
992 Match,
993 Mismatch,
994 Unavailable { reason: LaunchSpecUnavailableReason },
995}
996
997#[derive(Debug, Serialize, Deserialize)]
998#[serde(tag = "method", rename_all = "snake_case")]
999enum RunningImageEvidenceWire {
1000 LinuxProcSha256 {
1001 digest: String,
1002 },
1003 MacosSpawnInode {
1004 device: u64,
1005 inode: u64,
1006 },
1007 WindowsSpawnFileId {
1008 volume_serial_number: u64,
1009 file_id: [u8; 16],
1010 },
1011}
1012
1013#[derive(Debug, Serialize, Deserialize)]
1014#[serde(tag = "kind", rename_all = "snake_case")]
1015enum SupervisorRouteConsumerWire {
1016 Reserved { module_id: String },
1017 Direct { connection_id: u64 },
1018}
1019
1020#[derive(Debug, Serialize, Deserialize)]
1021#[serde(tag = "state", rename_all = "snake_case")]
1022enum StderrCaptureStateWire {
1023 Captured,
1024 Incomplete { reason: String },
1025 NotCaptured { reason: String },
1026}
1027
1028#[derive(Debug, Serialize, Deserialize)]
1029#[serde(tag = "status", rename_all = "snake_case")]
1030enum ChildResourceUsageWire {
1031 Measured(ChildResourceReading),
1032 Unavailable {
1033 reason: ChildResourceUnavailableReason,
1034 },
1035}
1036
1037#[derive(Debug, Serialize, Deserialize)]
1038#[serde(tag = "kind", rename_all = "snake_case")]
1039enum StderrTailEntryWire {
1040 Line {
1041 text: String,
1042 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1043 truncated: bool,
1044 #[serde(default, skip_serializing_if = "Option::is_none")]
1047 at_ms: Option<u64>,
1048 },
1049 ProcessStart,
1050}
1051
1052#[derive(Debug, Clone, PartialEq)]
1054pub enum OrderedJsonValue {
1055 Null,
1056 Bool(bool),
1057 Number(serde_json::Number),
1058 String(String),
1059 Array(Vec<Self>),
1060 Object(OrderedJsonObject),
1061}
1062
1063#[derive(Debug, Clone, PartialEq)]
1065pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1066
1067impl OrderedJsonObject {
1068 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1070 &self.0
1071 }
1072
1073 fn into_value(self) -> serde_json::Value {
1074 serde_json::Value::Object(
1075 self.0
1076 .into_iter()
1077 .map(|(key, value)| (key, value.into_value()))
1078 .collect(),
1079 )
1080 }
1081}
1082
1083impl OrderedJsonValue {
1084 fn into_value(self) -> serde_json::Value {
1085 match self {
1086 Self::Null => serde_json::Value::Null,
1087 Self::Bool(value) => serde_json::Value::Bool(value),
1088 Self::Number(value) => serde_json::Value::Number(value),
1089 Self::String(value) => serde_json::Value::String(value),
1090 Self::Array(values) => {
1091 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1092 }
1093 Self::Object(value) => value.into_value(),
1094 }
1095 }
1096}
1097
1098impl Serialize for OrderedJsonValue {
1099 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1100 where
1101 S: Serializer,
1102 {
1103 match self {
1104 Self::Null => serializer.serialize_unit(),
1105 Self::Bool(value) => serializer.serialize_bool(*value),
1106 Self::Number(value) => value.serialize(serializer),
1107 Self::String(value) => serializer.serialize_str(value),
1108 Self::Array(values) => values.serialize(serializer),
1109 Self::Object(value) => value.serialize(serializer),
1110 }
1111 }
1112}
1113
1114impl<'de> Deserialize<'de> for OrderedJsonValue {
1115 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1116 where
1117 D: Deserializer<'de>,
1118 {
1119 struct OrderedValueVisitor;
1120
1121 impl<'de> Visitor<'de> for OrderedValueVisitor {
1122 type Value = OrderedJsonValue;
1123
1124 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1125 formatter.write_str("a JSON value with ordered object members")
1126 }
1127
1128 fn visit_unit<E>(self) -> Result<Self::Value, E>
1129 where
1130 E: serde::de::Error,
1131 {
1132 Ok(OrderedJsonValue::Null)
1133 }
1134
1135 fn visit_none<E>(self) -> Result<Self::Value, E>
1136 where
1137 E: serde::de::Error,
1138 {
1139 Ok(OrderedJsonValue::Null)
1140 }
1141
1142 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1143 where
1144 D: Deserializer<'de>,
1145 {
1146 OrderedJsonValue::deserialize(deserializer)
1147 }
1148
1149 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1150 where
1151 E: serde::de::Error,
1152 {
1153 Ok(OrderedJsonValue::Bool(value))
1154 }
1155
1156 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1157 where
1158 E: serde::de::Error,
1159 {
1160 Ok(OrderedJsonValue::Number(value.into()))
1161 }
1162
1163 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1164 where
1165 E: serde::de::Error,
1166 {
1167 Ok(OrderedJsonValue::Number(value.into()))
1168 }
1169
1170 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1171 where
1172 E: serde::de::Error,
1173 {
1174 serde_json::Number::from_f64(value)
1175 .map(OrderedJsonValue::Number)
1176 .ok_or_else(|| E::custom("non-finite JSON number"))
1177 }
1178
1179 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1180 where
1181 E: serde::de::Error,
1182 {
1183 Ok(OrderedJsonValue::String(value.to_owned()))
1184 }
1185
1186 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1187 where
1188 E: serde::de::Error,
1189 {
1190 Ok(OrderedJsonValue::String(value))
1191 }
1192
1193 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1194 where
1195 A: SeqAccess<'de>,
1196 {
1197 let mut values = Vec::new();
1198 while let Some(value) = sequence.next_element()? {
1199 values.push(value);
1200 }
1201 Ok(OrderedJsonValue::Array(values))
1202 }
1203
1204 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1205 where
1206 A: MapAccess<'de>,
1207 {
1208 let mut entries = Vec::new();
1209 while let Some((key, value)) = map.next_entry()? {
1210 entries.push((key, value));
1211 }
1212 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1213 }
1214 }
1215
1216 deserializer.deserialize_any(OrderedValueVisitor)
1217 }
1218}
1219
1220impl Serialize for OrderedJsonObject {
1221 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1222 where
1223 S: Serializer,
1224 {
1225 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1226 for (key, value) in &self.0 {
1227 map.serialize_entry(key, value)?;
1228 }
1229 map.end()
1230 }
1231}
1232
1233impl<'de> Deserialize<'de> for OrderedJsonObject {
1234 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1235 where
1236 D: Deserializer<'de>,
1237 {
1238 struct OrderedObjectVisitor;
1239
1240 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1241 type Value = OrderedJsonObject;
1242
1243 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1244 formatter.write_str("an object with ordered JSON members")
1245 }
1246
1247 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1248 where
1249 A: MapAccess<'de>,
1250 {
1251 let mut entries = Vec::new();
1252 while let Some((key, value)) = map.next_entry()? {
1253 entries.push((key, value));
1254 }
1255 Ok(OrderedJsonObject(entries))
1256 }
1257 }
1258
1259 deserializer.deserialize_map(OrderedObjectVisitor)
1260 }
1261}
1262
1263fn read_tagged<'de, D>(
1264 deserializer: D,
1265 field: &'static str,
1266) -> Result<(String, OrderedJsonObject), D::Error>
1267where
1268 D: Deserializer<'de>,
1269{
1270 let body = OrderedJsonObject::deserialize(deserializer)?;
1271 let mut tag = None;
1272 for (key, value) in body.as_entries() {
1273 if key != field {
1274 continue;
1275 }
1276 if tag.is_some() {
1277 return Err(D::Error::custom(format!(
1278 "tagged object has duplicate `{field}` field"
1279 )));
1280 }
1281 let OrderedJsonValue::String(value) = value else {
1282 return Err(D::Error::custom(format!(
1283 "tagged object has no string `{field}` field"
1284 )));
1285 };
1286 tag = Some(value);
1287 }
1288 let Some(tag) = tag else {
1289 return Err(D::Error::custom(format!(
1290 "tagged object has no string `{field}` field"
1291 )));
1292 };
1293 Ok((tag.to_string(), body))
1294}
1295
1296fn read_ordered_tagged(
1297 value: OrderedJsonValue,
1298 field: &'static str,
1299) -> Result<(String, OrderedJsonObject), String> {
1300 let OrderedJsonValue::Object(body) = value else {
1301 return Err(format!("expected tagged object with `{field}` field"));
1302 };
1303 let mut tag = None;
1304 for (key, value) in body.as_entries() {
1305 if key != field {
1306 continue;
1307 }
1308 if tag.is_some() {
1309 return Err(format!("tagged object has duplicate `{field}` field"));
1310 }
1311 let OrderedJsonValue::String(value) = value else {
1312 return Err(format!("tagged object has no string `{field}` field"));
1313 };
1314 tag = Some(value);
1315 }
1316 let Some(tag) = tag else {
1317 return Err(format!("tagged object has no string `{field}` field"));
1318 };
1319 Ok((tag.to_string(), body))
1320}
1321
1322fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1323 body.as_entries()
1324 .iter()
1325 .find_map(|(key, value)| (key == field).then_some(value))
1326}
1327
1328fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1329 match ordered_field(body, field) {
1330 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1331 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1332 None => Err(format!("tagged object has no `{field}` field")),
1333 }
1334}
1335
1336fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1337 let (tag, body) = read_ordered_tagged(value, "method")?;
1338 match tag.as_str() {
1339 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1340 digest: ordered_string(&body, "digest")?,
1341 }),
1342 "macos_spawn_inode" => {
1343 let device = ordered_field(&body, "device")
1344 .and_then(|value| match value {
1345 OrderedJsonValue::Number(number) => number.as_u64(),
1346 _ => None,
1347 })
1348 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1349 let inode = ordered_field(&body, "inode")
1350 .and_then(|value| match value {
1351 OrderedJsonValue::Number(number) => number.as_u64(),
1352 _ => None,
1353 })
1354 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1355 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1356 }
1357 "windows_spawn_file_id" => {
1358 let wire: RunningImageEvidenceWire = serde_json::from_value(
1359 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1360 )
1361 .map_err(|error| error.to_string())?;
1362 match wire {
1363 RunningImageEvidenceWire::WindowsSpawnFileId {
1364 volume_serial_number,
1365 file_id,
1366 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1367 volume_serial_number,
1368 file_id,
1369 }),
1370 _ => unreachable!(),
1371 }
1372 }
1373 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1374 }
1375}
1376
1377impl Serialize for ModuleDeclaredProvenance {
1378 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1379 where
1380 S: Serializer,
1381 {
1382 match self {
1383 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1384 build: build.clone(),
1385 }
1386 .serialize(serializer),
1387 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1388 Self::Unknown { body, .. } => body.serialize(serializer),
1389 }
1390 }
1391}
1392
1393impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1394 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1395 where
1396 D: serde::Deserializer<'de>,
1397 {
1398 let (tag, value) = read_tagged(deserializer, "status")?;
1399 match tag.as_str() {
1400 "reported" => match serde_json::from_value(value.into_value())
1401 .map_err(D::Error::custom)?
1402 {
1403 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1404 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1405 },
1406 "unverifiable" => {
1407 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1408 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1409 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1410 }
1411 }
1412 _ => Ok(Self::Unknown { tag, body: value }),
1413 }
1414 }
1415}
1416
1417impl Serialize for RunningImageAgreement {
1418 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1419 where
1420 S: Serializer,
1421 {
1422 match self {
1423 Self::Match { evidence } => RunningImageAgreementWire::Match {
1424 evidence: evidence.clone(),
1425 }
1426 .serialize(serializer),
1427 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1428 running: running.clone(),
1429 disk: disk.clone(),
1430 }
1431 .serialize(serializer),
1432 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1433 reason: reason.clone(),
1434 }
1435 .serialize(serializer),
1436 Self::Unknown { body, .. } => body.serialize(serializer),
1437 }
1438 }
1439}
1440
1441impl Serialize for ReloadPathAgreement {
1442 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1443 where
1444 S: Serializer,
1445 {
1446 match self {
1447 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1448 Self::Mismatch {
1449 configured,
1450 spawned_from,
1451 } => ReloadPathAgreementWire::Mismatch {
1452 configured: configured.clone(),
1453 spawned_from: spawned_from.clone(),
1454 }
1455 .serialize(serializer),
1456 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1457 reason: reason.clone(),
1458 }
1459 .serialize(serializer),
1460 Self::Unknown { body, .. } => body.serialize(serializer),
1461 }
1462 }
1463}
1464
1465impl Serialize for LaunchSpecAgreement {
1466 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1467 where
1468 S: Serializer,
1469 {
1470 match self {
1471 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1472 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1473 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1474 reason: reason.clone(),
1475 }
1476 .serialize(serializer),
1477 Self::Unknown { body, .. } => body.serialize(serializer),
1478 }
1479 }
1480}
1481
1482impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1483 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1484 where
1485 D: Deserializer<'de>,
1486 {
1487 let (tag, body) = read_tagged(deserializer, "status")?;
1488 match tag.as_str() {
1489 "match" => Ok(Self::Match),
1490 "mismatch" => Ok(Self::Mismatch),
1491 "unavailable" => match serde_json::from_value(body.into_value())
1492 .map_err(D::Error::custom)?
1493 {
1494 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1495 _ => unreachable!(),
1496 },
1497 _ => Ok(Self::Unknown { tag, body }),
1498 }
1499 }
1500}
1501
1502impl<'de> Deserialize<'de> for ReloadPathAgreement {
1503 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1504 where
1505 D: Deserializer<'de>,
1506 {
1507 let (tag, body) = read_tagged(deserializer, "status")?;
1508 match tag.as_str() {
1509 "match" => Ok(Self::Match),
1510 "mismatch" => {
1511 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1512 ReloadPathAgreementWire::Mismatch {
1513 configured,
1514 spawned_from,
1515 } => Ok(Self::Mismatch {
1516 configured,
1517 spawned_from,
1518 }),
1519 _ => unreachable!(),
1520 }
1521 }
1522 "unavailable" => match serde_json::from_value(body.into_value())
1523 .map_err(D::Error::custom)?
1524 {
1525 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1526 _ => unreachable!(),
1527 },
1528 _ => Ok(Self::Unknown { tag, body }),
1529 }
1530 }
1531}
1532
1533impl<'de> Deserialize<'de> for RunningImageAgreement {
1534 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1535 where
1536 D: serde::Deserializer<'de>,
1537 {
1538 let (tag, value) = read_tagged(deserializer, "status")?;
1539 match tag.as_str() {
1540 "match" => Ok(Self::Match {
1541 evidence: decode_running_image_evidence(
1542 ordered_field(&value, "evidence")
1543 .cloned()
1544 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1545 )
1546 .map_err(D::Error::custom)?,
1547 }),
1548 "mismatch" => Ok(Self::Mismatch {
1549 running: decode_running_image_evidence(
1550 ordered_field(&value, "running")
1551 .cloned()
1552 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1553 )
1554 .map_err(D::Error::custom)?,
1555 disk: decode_running_image_evidence(
1556 ordered_field(&value, "disk")
1557 .cloned()
1558 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1559 )
1560 .map_err(D::Error::custom)?,
1561 }),
1562 "unavailable" => Ok(Self::Unavailable {
1563 reason: serde_json::from_value(
1564 ordered_field(&value, "reason")
1565 .cloned()
1566 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1567 .into_value(),
1568 )
1569 .map_err(D::Error::custom)?,
1570 }),
1571 _ => Ok(Self::Unknown { tag, body: value }),
1572 }
1573 }
1574}
1575
1576impl Serialize for ChildResourceUsage {
1577 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1578 where
1579 S: Serializer,
1580 {
1581 match self {
1582 Self::Measured(reading) => {
1583 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1584 }
1585 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1586 reason: reason.clone(),
1587 }
1588 .serialize(serializer),
1589 Self::Unknown { body, .. } => body.serialize(serializer),
1590 }
1591 }
1592}
1593
1594impl<'de> Deserialize<'de> for ChildResourceUsage {
1595 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1596 where
1597 D: Deserializer<'de>,
1598 {
1599 let (tag, body) = read_tagged(deserializer, "status")?;
1600 match tag.as_str() {
1601 "measured" | "unavailable" => {
1602 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1603 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1604 ChildResourceUsageWire::Unavailable { reason } => {
1605 Ok(Self::Unavailable { reason })
1606 }
1607 }
1608 }
1609 _ => Ok(Self::Unknown { tag, body }),
1610 }
1611 }
1612}
1613
1614impl Serialize for RunningImageEvidence {
1615 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1616 where
1617 S: Serializer,
1618 {
1619 match self {
1620 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1621 digest: digest.clone(),
1622 }
1623 .serialize(serializer),
1624 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1625 device: *device,
1626 inode: *inode,
1627 }
1628 .serialize(serializer),
1629 Self::WindowsSpawnFileId {
1630 volume_serial_number,
1631 file_id,
1632 } => RunningImageEvidenceWire::WindowsSpawnFileId {
1633 volume_serial_number: *volume_serial_number,
1634 file_id: *file_id,
1635 }
1636 .serialize(serializer),
1637 Self::Unknown { body, .. } => body.serialize(serializer),
1638 }
1639 }
1640}
1641
1642impl<'de> Deserialize<'de> for RunningImageEvidence {
1643 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1644 where
1645 D: serde::Deserializer<'de>,
1646 {
1647 let (tag, value) = read_tagged(deserializer, "method")?;
1648 match tag.as_str() {
1649 "linux_proc_sha256" => {
1650 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1651 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1652 Ok(Self::LinuxProcSha256 { digest })
1653 }
1654 _ => unreachable!(),
1655 }
1656 }
1657 "macos_spawn_inode" => {
1658 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1659 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1660 Ok(Self::MacosSpawnInode { device, inode })
1661 }
1662 _ => unreachable!(),
1663 }
1664 }
1665 "windows_spawn_file_id" => {
1666 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1667 RunningImageEvidenceWire::WindowsSpawnFileId {
1668 volume_serial_number,
1669 file_id,
1670 } => Ok(Self::WindowsSpawnFileId {
1671 volume_serial_number,
1672 file_id,
1673 }),
1674 _ => unreachable!(),
1675 }
1676 }
1677 _ => Ok(Self::Unknown { tag, body: value }),
1678 }
1679 }
1680}
1681
1682impl Serialize for SupervisorRouteConsumer {
1683 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1684 where
1685 S: Serializer,
1686 {
1687 match self {
1688 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1689 module_id: module_id.clone(),
1690 }
1691 .serialize(serializer),
1692 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1693 connection_id: *connection_id,
1694 }
1695 .serialize(serializer),
1696 Self::Unknown { body, .. } => body.serialize(serializer),
1697 }
1698 }
1699}
1700
1701impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1702 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1703 where
1704 D: serde::Deserializer<'de>,
1705 {
1706 let (tag, value) = read_tagged(deserializer, "kind")?;
1707 match tag.as_str() {
1708 "reserved" => {
1709 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1710 SupervisorRouteConsumerWire::Reserved { module_id } => {
1711 Ok(Self::Reserved { module_id })
1712 }
1713 _ => unreachable!(),
1714 }
1715 }
1716 "direct" => {
1717 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1718 SupervisorRouteConsumerWire::Direct { connection_id } => {
1719 Ok(Self::Direct { connection_id })
1720 }
1721 _ => unreachable!(),
1722 }
1723 }
1724 _ => Ok(Self::Unknown { tag, body: value }),
1725 }
1726 }
1727}
1728
1729impl Serialize for StderrCaptureState {
1730 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1731 where
1732 S: Serializer,
1733 {
1734 match self {
1735 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1736 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1737 reason: reason.clone(),
1738 }
1739 .serialize(serializer),
1740 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1741 reason: reason.clone(),
1742 }
1743 .serialize(serializer),
1744 Self::Unknown { body, .. } => body.serialize(serializer),
1745 }
1746 }
1747}
1748
1749impl<'de> Deserialize<'de> for StderrCaptureState {
1750 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1751 where
1752 D: serde::Deserializer<'de>,
1753 {
1754 let (tag, value) = read_tagged(deserializer, "state")?;
1755 match tag.as_str() {
1756 "captured" => {
1757 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1758 StderrCaptureStateWire::Captured => Ok(Self::Captured),
1759 _ => unreachable!(),
1760 }
1761 }
1762 "incomplete" => match serde_json::from_value(value.into_value())
1763 .map_err(D::Error::custom)?
1764 {
1765 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1766 _ => unreachable!(),
1767 },
1768 "not_captured" => match serde_json::from_value(value.into_value())
1769 .map_err(D::Error::custom)?
1770 {
1771 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1772 _ => unreachable!(),
1773 },
1774 _ => Ok(Self::Unknown { tag, body: value }),
1775 }
1776 }
1777}
1778
1779impl Serialize for StderrTailEntry {
1780 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1781 where
1782 S: Serializer,
1783 {
1784 match self {
1785 Self::Line {
1786 text,
1787 truncated,
1788 at_ms,
1789 } => StderrTailEntryWire::Line {
1790 text: text.clone(),
1791 truncated: *truncated,
1792 at_ms: *at_ms,
1793 }
1794 .serialize(serializer),
1795 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1796 Self::Unknown { body, .. } => body.serialize(serializer),
1797 }
1798 }
1799}
1800
1801impl<'de> Deserialize<'de> for StderrTailEntry {
1802 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1803 where
1804 D: serde::Deserializer<'de>,
1805 {
1806 let (tag, value) = read_tagged(deserializer, "kind")?;
1807 match tag.as_str() {
1808 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1809 StderrTailEntryWire::Line {
1810 text,
1811 truncated,
1812 at_ms,
1813 } => Ok(Self::Line {
1814 text,
1815 truncated,
1816 at_ms,
1817 }),
1818 _ => unreachable!(),
1819 },
1820 "process_start" => {
1821 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1822 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1823 _ => unreachable!(),
1824 }
1825 }
1826 _ => Ok(Self::Unknown { tag, body: value }),
1827 }
1828 }
1829}
1830
1831fn is_zero_u64(value: &u64) -> bool {
1832 *value == 0
1833}
1834
1835fn default_true() -> bool {
1836 true
1837}
1838
1839#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1841pub struct TerminalHistory {
1842 pub daemon_started_at_ms: u64,
1844 pub entries: Vec<TerminalEntry>,
1845 #[serde(default, skip_serializing_if = "is_zero_u64")]
1848 pub dropped: u64,
1849 #[serde(default, skip_serializing_if = "is_zero_u64")]
1852 pub journal_skipped_lines: u64,
1853 #[serde(default, skip_serializing_if = "is_zero_u64")]
1855 pub journal_read_errors: u64,
1856 #[serde(default, skip_serializing_if = "is_zero_u64")]
1858 pub journal_write_failures: u64,
1859}
1860
1861#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1863pub struct TerminalEntry {
1864 #[serde(default, skip_serializing_if = "Option::is_none")]
1867 pub daemon_incarnation: Option<String>,
1868 #[serde(default, skip_serializing_if = "Option::is_none")]
1869 pub exit_code: Option<i32>,
1870 #[serde(default, skip_serializing_if = "Option::is_none")]
1871 pub exit_signal: Option<i32>,
1872 pub at_ms: u64,
1873 pub disposition: TerminalDisposition,
1874 #[serde(default, skip_serializing_if = "Option::is_none")]
1878 pub exit_kind: Option<TerminalExitKind>,
1879 #[serde(default, skip_serializing_if = "Option::is_none")]
1886 pub disposition_detail: Option<String>,
1887}
1888
1889#[derive(Debug, Clone, PartialEq, Eq)]
1894pub enum TerminalExitKind {
1895 Clean,
1896 Crash,
1897 DeliberateSeverance,
1898 Unknown(String),
1899}
1900
1901impl TerminalExitKind {
1902 fn wire_name(&self) -> &str {
1903 match self {
1904 Self::Clean => "clean",
1905 Self::Crash => "crash",
1906 Self::DeliberateSeverance => "deliberate_severance",
1907 Self::Unknown(value) => value,
1908 }
1909 }
1910}
1911
1912impl Serialize for TerminalExitKind {
1913 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1914 where
1915 S: serde::Serializer,
1916 {
1917 serializer.serialize_str(self.wire_name())
1918 }
1919}
1920
1921impl<'de> Deserialize<'de> for TerminalExitKind {
1922 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1923 where
1924 D: serde::Deserializer<'de>,
1925 {
1926 let value = String::deserialize(deserializer)?;
1927 Ok(match value.as_str() {
1928 "clean" => Self::Clean,
1929 "crash" => Self::Crash,
1930 "deliberate_severance" => Self::DeliberateSeverance,
1931 _ => Self::Unknown(value),
1932 })
1933 }
1934}
1935
1936open_string_enum! {
1937 TerminalDisposition {
1939 Stopped => "stopped",
1940 Disabled => "disabled",
1941 Failed => "failed",
1942 Restarting => "restarting",
1943 DaemonShutdown => "daemon_shutdown",
1948 }
1949}
1950
1951#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1952#[serde(rename_all = "snake_case")]
1953pub enum PollKind {
1954 Status,
1955 Liveness,
1956}
1957
1958#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1970#[non_exhaustive]
1971pub struct CatalogEntry {
1972 pub module_id: String,
1973 #[serde(default = "default_true")]
1984 pub ready: bool,
1985 #[serde(default, skip_serializing_if = "Option::is_none")]
1989 pub not_ready: Option<NotReadyReason>,
1990 #[serde(default, skip_serializing_if = "Option::is_none")]
2011 pub module_version: Option<String>,
2012 pub roles: Vec<ProviderRole>,
2013 pub control_ops: Vec<String>,
2014 #[serde(default, skip_serializing_if = "Option::is_none")]
2019 pub capabilities: Option<CapabilityDeclarations>,
2020 #[serde(default, skip_serializing_if = "Option::is_none")]
2023 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2024 #[serde(default, skip_serializing_if = "Option::is_none")]
2028 pub events: Option<Vec<EventDeclaration>>,
2029 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2032 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2033}
2034
2035impl CatalogEntry {
2036 #[must_use]
2038 pub fn new(
2039 module_id: impl Into<String>,
2040 roles: Vec<ProviderRole>,
2041 control_ops: Vec<String>,
2042 ) -> Self {
2043 Self {
2044 module_id: module_id.into(),
2045 ready: default_true(),
2046 not_ready: None,
2047 module_version: None,
2048 roles,
2049 control_ops,
2050 capabilities: None,
2051 self_signals: None,
2052 events: None,
2053 operation_delivery: BTreeMap::new(),
2054 }
2055 }
2056
2057 #[must_use]
2059 pub fn with_ready(mut self, ready: bool) -> Self {
2060 self.ready = ready;
2061 self
2062 }
2063
2064 #[must_use]
2066 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2067 self.not_ready = not_ready;
2068 self
2069 }
2070
2071 #[must_use]
2073 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2074 self.module_version = module_version;
2075 self
2076 }
2077
2078 #[must_use]
2080 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2081 self.capabilities = capabilities;
2082 self
2083 }
2084
2085 #[must_use]
2087 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2088 self.self_signals = self_signals;
2089 self
2090 }
2091
2092 #[must_use]
2094 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2095 self.events = events;
2096 self
2097 }
2098
2099 #[must_use]
2102 pub fn with_operation_delivery(
2103 mut self,
2104 operation_delivery: BTreeMap<String, OperationDelivery>,
2105 ) -> Self {
2106 self.operation_delivery = operation_delivery;
2107 self
2108 }
2109}
2110
2111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2113pub struct NotReadyReason {
2114 pub reason: String,
2119 #[serde(default, skip_serializing_if = "Option::is_none")]
2122 pub capability: Option<String>,
2123}
2124
2125impl NotReadyReason {
2126 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2127 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2128}
2129
2130#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2131pub struct CapabilityRequirementStatus {
2132 pub consumer: String,
2133 pub capability: String,
2134 pub need: String,
2135 pub verdict: String,
2136 pub episode_seq: u64,
2137 pub config_satisfiable: bool,
2138 pub runtime_available: bool,
2139 pub detail: String,
2140}
2141
2142#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2143pub struct SupervisorRescanResult {
2144 pub added: Vec<String>,
2145 pub removed: Vec<String>,
2146 pub changed_pending_reload: Vec<String>,
2147 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2160 pub enabled_changes: Vec<String>,
2161 pub unchanged: u32,
2162 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2170 pub preview: bool,
2171 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2189 pub restart_required: Vec<String>,
2190 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2194 pub capability_warnings: Vec<String>,
2195 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2202 pub module_actions: Vec<RescanModuleAction>,
2203 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2207 pub earlier_pending: Vec<String>,
2208 #[serde(default, skip_serializing_if = "Option::is_none")]
2211 pub expect: Option<RescanExpect>,
2212}
2213
2214#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2230#[serde(rename_all = "snake_case")]
2231pub enum ModuleProtocol {
2232 #[default]
2236 Subc,
2237 None,
2246}
2247
2248#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2260#[non_exhaustive]
2261pub struct SupervisorEntry {
2262 #[serde(default, skip_serializing_if = "Option::is_none")]
2265 pub waiting_for_previous_pid: Option<u32>,
2266 pub module_id: String,
2267 pub state: String,
2268 pub enabled: bool,
2269 pub live: bool,
2279 #[serde(default)]
2283 pub protocol: ModuleProtocol,
2284 #[serde(default, skip_serializing_if = "Option::is_none")]
2287 pub launch_nonce_env: Option<bool>,
2288 #[serde(default, skip_serializing_if = "Option::is_none")]
2294 pub launch_nonce_source: Option<String>,
2295 pub health: SupervisorHealthStatus,
2296 #[serde(default, skip_serializing_if = "Option::is_none")]
2299 pub pending_reload: Option<PendingReloadVerdict>,
2300 #[serde(default)]
2306 pub last_probe_ms: Option<u64>,
2307 #[serde(default, skip_serializing_if = "Option::is_none")]
2311 pub last_exit_code: Option<i32>,
2312 #[serde(default, skip_serializing_if = "Option::is_none")]
2316 pub last_exit_signal: Option<i32>,
2317 #[serde(default, skip_serializing_if = "Option::is_none")]
2321 pub last_exit_ms: Option<u64>,
2322 #[serde(default, skip_serializing_if = "Option::is_none")]
2325 pub last_exit_kind: Option<TerminalExitKind>,
2326 #[serde(default, skip_serializing_if = "Option::is_none")]
2343 pub restart_count: Option<u32>,
2344 #[serde(default, skip_serializing_if = "Option::is_none")]
2347 pub max_restarts: Option<u32>,
2348 #[serde(default, skip_serializing_if = "Option::is_none")]
2351 pub lifetime_restarts: Option<u32>,
2352 #[serde(default, skip_serializing_if = "Option::is_none")]
2356 pub spawn_generation: Option<u64>,
2357 #[serde(default, skip_serializing_if = "Option::is_none")]
2367 pub restart_window_secs: Option<u64>,
2368 #[serde(default, skip_serializing_if = "Option::is_none")]
2372 pub drain_timeout_ms: Option<u64>,
2373 #[serde(default, skip_serializing_if = "Option::is_none")]
2376 pub restart_backoff_ms: Option<u64>,
2377 #[serde(default, skip_serializing_if = "Option::is_none")]
2380 pub restart_max_backoff_ms: Option<u64>,
2381 #[serde(default, skip_serializing_if = "Option::is_none")]
2394 pub resources: Option<ChildResourceUsage>,
2395}
2396
2397impl SupervisorEntry {
2398 #[must_use]
2400 pub fn new(
2401 module_id: impl Into<String>,
2402 state: impl Into<String>,
2403 enabled: bool,
2404 live: bool,
2405 health: SupervisorHealthStatus,
2406 ) -> Self {
2407 Self {
2408 module_id: module_id.into(),
2409 state: state.into(),
2410 waiting_for_previous_pid: None,
2411 enabled,
2412 live,
2413 protocol: ModuleProtocol::default(),
2414 launch_nonce_env: None,
2415 launch_nonce_source: None,
2416 health,
2417 pending_reload: None,
2418 last_probe_ms: None,
2419 last_exit_code: None,
2420 last_exit_signal: None,
2421 last_exit_ms: None,
2422 last_exit_kind: None,
2423 restart_count: None,
2424 max_restarts: None,
2425 lifetime_restarts: None,
2426 spawn_generation: None,
2427 restart_window_secs: None,
2428 drain_timeout_ms: None,
2429 restart_backoff_ms: None,
2430 restart_max_backoff_ms: None,
2431 resources: None,
2432 }
2433 }
2434
2435 #[must_use]
2437 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2438 self.protocol = protocol;
2439 self
2440 }
2441
2442 #[must_use]
2444 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2445 self.launch_nonce_env = launch_nonce_env;
2446 self
2447 }
2448
2449 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2450 self.launch_nonce_source = source;
2451 self
2452 }
2453
2454 #[must_use]
2455 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2456 self.waiting_for_previous_pid = pid;
2457 self
2458 }
2459
2460 #[must_use]
2462 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2463 self.pending_reload = pending_reload;
2464 self
2465 }
2466
2467 #[must_use]
2469 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2470 self.last_probe_ms = last_probe_ms;
2471 self
2472 }
2473
2474 #[must_use]
2476 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2477 self.last_exit_code = last_exit_code;
2478 self
2479 }
2480
2481 #[must_use]
2483 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2484 self.last_exit_signal = last_exit_signal;
2485 self
2486 }
2487
2488 #[must_use]
2490 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2491 self.last_exit_ms = last_exit_ms;
2492 self
2493 }
2494
2495 #[must_use]
2497 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2498 self.last_exit_kind = last_exit_kind;
2499 self
2500 }
2501
2502 #[must_use]
2504 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2505 self.restart_count = restart_count;
2506 self
2507 }
2508
2509 #[must_use]
2511 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2512 self.max_restarts = max_restarts;
2513 self
2514 }
2515
2516 #[must_use]
2518 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2519 self.lifetime_restarts = lifetime_restarts;
2520 self
2521 }
2522
2523 #[must_use]
2525 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2526 self.spawn_generation = spawn_generation;
2527 self
2528 }
2529
2530 #[must_use]
2532 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2533 self.restart_window_secs = restart_window_secs;
2534 self
2535 }
2536
2537 #[must_use]
2539 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2540 self.drain_timeout_ms = drain_timeout_ms;
2541 self
2542 }
2543
2544 #[must_use]
2546 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2547 self.restart_backoff_ms = restart_backoff_ms;
2548 self
2549 }
2550
2551 #[must_use]
2553 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2554 self.restart_max_backoff_ms = restart_max_backoff_ms;
2555 self
2556 }
2557
2558 #[must_use]
2560 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2561 self.resources = resources;
2562 self
2563 }
2564}
2565
2566#[derive(Debug, Clone, PartialEq)]
2569pub enum ChildResourceUsage {
2570 Measured(ChildResourceReading),
2571 Unavailable {
2572 reason: ChildResourceUnavailableReason,
2573 },
2574 Unknown {
2577 tag: String,
2578 body: OrderedJsonObject,
2579 },
2580}
2581
2582#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2584pub struct ChildResourceReading {
2585 pub memory_bytes: u64,
2588 pub memory_kind: ChildMemoryKind,
2589 #[serde(default, skip_serializing_if = "Option::is_none")]
2592 pub swap_bytes: Option<u64>,
2593 pub cpu_user_ms: u64,
2597 pub cpu_system_ms: u64,
2600}
2601
2602open_string_enum! {
2603 ChildMemoryKind {
2605 PhysFootprint => "phys_footprint",
2609 ResidentSet => "resident_set",
2612 WindowsWorkingSet => "windows_working_set",
2615 }
2616}
2617
2618open_string_enum! {
2619 ChildResourceUnavailableReason {
2621 NotRunning => "not_running",
2623 UnsupportedPlatform => "unsupported_platform",
2625 Unreadable => "unreadable",
2628 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2631 }
2632}
2633
2634#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2635#[serde(rename_all = "snake_case")]
2636pub enum SupervisorHealthStatus {
2637 Ok,
2638 Degraded,
2639 Failing,
2640 Unresponsive,
2641 Unknown,
2642}
2643
2644#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2645pub struct SupervisorHealthEntry {
2646 pub module_id: String,
2647 pub status: SupervisorHealthStatus,
2648 #[serde(default, skip_serializing_if = "Option::is_none")]
2654 pub detail: Option<String>,
2655 #[serde(default, skip_serializing_if = "Option::is_none")]
2660 pub metrics: Option<serde_json::Value>,
2661 pub consecutive_failures: u32,
2662 #[serde(default)]
2665 pub late_answer_count: u64,
2666 #[serde(default, skip_serializing_if = "Option::is_none")]
2668 pub last_late_answer_latency_ms: Option<u64>,
2669 #[serde(default)]
2674 pub last_action: Option<String>,
2675 #[serde(default)]
2678 pub last_action_ms: Option<u64>,
2679 #[serde(default, skip_serializing_if = "Option::is_none")]
2692 pub last_probe_ms: Option<u64>,
2693}
2694
2695#[cfg(test)]
2696mod tests {
2697 #[test]
2698 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2699 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2700 volume_serial_number: u64::MAX,
2701 file_id: [
2702 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2703 ],
2704 };
2705 let agreement = super::RunningImageAgreement::Match { evidence };
2706 let encoded = serde_json::to_string(&agreement).unwrap();
2707 assert!(encoded.contains("windows_spawn_file_id"));
2708 assert_eq!(
2709 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
2710 agreement
2711 );
2712 }
2713
2714 #[test]
2715 fn unix_running_image_evidence_keeps_original_wire_bytes() {
2716 assert_eq!(
2717 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
2718 device: 7,
2719 inode: 11
2720 })
2721 .unwrap(),
2722 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
2723 );
2724 assert_eq!(
2725 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
2726 digest: "abc".to_owned()
2727 })
2728 .unwrap(),
2729 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
2730 );
2731 }
2732 use super::*;
2733 use subc_protocol::{BindIdentity, RouteTarget};
2734
2735 #[test]
2736 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2737 let entry = TerminalEntry {
2738 daemon_incarnation: Some("daemon-before-restart".into()),
2739 exit_code: Some(1),
2740 exit_signal: None,
2741 at_ms: 1_700_000_000_123,
2742 disposition: TerminalDisposition::Restarting,
2743 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2744 disposition_detail: None,
2745 };
2746 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2747 assert_eq!(
2748 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2749 ["exit_kind"],
2750 "deliberate_severance"
2751 );
2752
2753 #[derive(serde::Deserialize)]
2754 struct LegacyTerminalEntry {
2755 exit_code: Option<i32>,
2756 exit_signal: Option<i32>,
2757 at_ms: u64,
2758 disposition: TerminalDisposition,
2759 }
2760
2761 let decoded: LegacyTerminalEntry =
2762 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2763 assert_eq!(decoded.exit_code, Some(1));
2764 assert_eq!(decoded.exit_signal, None);
2765 assert_eq!(decoded.at_ms, 1_700_000_000_123);
2766 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
2767
2768 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
2769 let future: TerminalEntry =
2770 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
2771 assert_eq!(
2772 future.exit_kind,
2773 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
2774 );
2775 }
2776
2777 #[test]
2778 fn terminal_incarnation_is_optional_for_older_daemons() {
2779 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
2780 "at_ms": 123,
2781 "disposition": "stopped"
2782 }))
2783 .unwrap();
2784 let encoded = serde_json::to_value(&entry).unwrap();
2785 assert_eq!(
2786 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
2787 (None, None)
2788 );
2789 }
2790
2791 #[test]
2792 fn route_poll_uses_kind_field() {
2793 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
2794 route_channel: 7,
2795 route_epoch: 11,
2796 kind: PollKind::Status,
2797 })
2798 .unwrap();
2799
2800 assert_eq!(body["op"], "route.poll");
2801 assert_eq!(body["route_epoch"], 11);
2802 assert_eq!(body["kind"], "status");
2803 assert!(body.get("op").is_some());
2804 }
2805
2806 #[test]
2807 fn route_open_is_internally_tagged() {
2808 let request = ClientControlRequest::RouteOpen {
2809 target: RouteTarget::ToolProvider {
2810 module_id: "aft".to_string(),
2811 },
2812 identity: BindIdentity::new("/tmp/project", "opencode", "session-1"),
2813 consumer_identity: None,
2814 consumer_capabilities: None,
2815 role_versions: None,
2816 admission_facts: None,
2817 scope: None,
2818 };
2819
2820 let body = serde_json::to_value(request).unwrap();
2821 assert_eq!(body["op"], "route.open");
2822 assert_eq!(body["target"]["kind"], "tool_provider");
2823 assert!(body.get("consumer_identity").is_none());
2824 assert!(body.get("consumer_capabilities").is_none());
2825 assert!(body.get("role_versions").is_none());
2826 }
2827
2828 #[test]
2829 fn route_open_without_optional_fields_still_decodes() {
2830 let body = serde_json::json!({
2831 "op": "route.open",
2832 "target": { "kind": "tool_provider", "module_id": "aft" },
2833 "identity": {
2834 "project_root": "/tmp/project",
2835 "harness": "opencode",
2836 "session": "session-1"
2837 }
2838 });
2839
2840 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
2841 let ClientControlRequest::RouteOpen {
2842 consumer_identity,
2843 consumer_capabilities,
2844 role_versions,
2845 admission_facts,
2846 ..
2847 } = decoded
2848 else {
2849 panic!("decoded wrong request variant");
2850 };
2851 assert_eq!(consumer_identity, None);
2852 assert_eq!(consumer_capabilities, None);
2853 assert_eq!(role_versions, None);
2854 assert_eq!(admission_facts, None);
2855 }
2856
2857 #[test]
2858 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
2859 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
2860 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
2861 match decoded {
2862 ClientControlPush::RouteClosed {
2863 excluded_subscriptions,
2864 terminal,
2865 ..
2866 } => {
2867 assert_eq!(excluded_subscriptions, 0);
2868 assert_eq!(terminal, None);
2869 }
2870 other => panic!("unexpected push: {other:?}"),
2871 }
2872 assert!(!serde_json::to_string(&decoded)
2873 .unwrap()
2874 .contains("terminal"));
2875 }
2876
2877 #[test]
2878 fn old_route_closed_decoder_ignores_new_terminal_field() {
2879 #[derive(serde::Deserialize)]
2880 #[serde(tag = "op")]
2881 enum LegacyClientControlPush {
2882 #[serde(rename = "route.closed")]
2883 RouteClosed {
2884 module_id: String,
2885 reason: RouteCloseReason,
2886 drained: bool,
2887 abandoned: u32,
2888 },
2889 }
2890
2891 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
2892 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
2893 match decoded {
2894 LegacyClientControlPush::RouteClosed {
2895 module_id,
2896 reason,
2897 drained,
2898 abandoned,
2899 } => {
2900 assert_eq!(module_id, "aft-tools");
2901 assert_eq!(reason, RouteCloseReason::Crash);
2902 assert!(!drained);
2903 assert_eq!(abandoned, 0);
2904 }
2905 }
2906 }
2907
2908 #[test]
2909 fn supervisor_routes_is_a_control_plane_request() {
2910 let body = serde_json::json!({
2911 "op": "supervisor.routes",
2912 "module_id": "aft"
2913 });
2914
2915 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
2916 assert_eq!(serde_json::to_value(request).unwrap(), body);
2917 }
2918
2919 #[test]
2920 fn diagnostic_string_enums_retain_unknown_wire_values() {
2921 let reason: RunningImageUnavailableReason =
2922 serde_json::from_str("\"future_reason\"").unwrap();
2923 let disposition: TerminalDisposition =
2924 serde_json::from_str("\"future_disposition\"").unwrap();
2925
2926 assert_eq!(
2927 reason,
2928 RunningImageUnavailableReason::Unknown("future_reason".to_string())
2929 );
2930 assert_eq!(
2931 disposition,
2932 TerminalDisposition::Unknown("future_disposition".to_string())
2933 );
2934 }
2935
2936 #[test]
2937 fn diagnostic_string_enums_preserve_existing_wire_names() {
2938 let names = [
2939 (RunningImageUnavailableReason::NotRunning, "not_running"),
2940 (
2941 RunningImageUnavailableReason::UnsupportedPlatform,
2942 "unsupported_platform",
2943 ),
2944 (
2945 RunningImageUnavailableReason::RunningExecutableUnreadable,
2946 "running_executable_unreadable",
2947 ),
2948 (
2949 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
2950 "running_executable_permission_denied",
2951 ),
2952 (
2953 RunningImageUnavailableReason::ProcessHidden,
2954 "process_hidden",
2955 ),
2956 (
2957 RunningImageUnavailableReason::SpawnedPathUnreadable,
2958 "spawned_path_unreadable",
2959 ),
2960 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
2961 (
2962 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
2963 "process_identity_unconfirmed",
2964 ),
2965 ];
2966 for (value, expected) in names {
2967 let wire = serde_json::to_string(&value).unwrap();
2968 assert_eq!(wire, format!("\"{expected}\""));
2969 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
2970 assert_eq!(decoded, value);
2971 }
2972
2973 for (value, expected) in [
2974 (TerminalDisposition::Stopped, "stopped"),
2975 (TerminalDisposition::Disabled, "disabled"),
2976 (TerminalDisposition::Failed, "failed"),
2977 (TerminalDisposition::Restarting, "restarting"),
2978 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
2979 ] {
2980 let wire = serde_json::to_string(&value).unwrap();
2981 assert_eq!(wire, format!("\"{expected}\""));
2982 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
2983 assert_eq!(decoded, value);
2984 }
2985 }
2986
2987 #[test]
2988 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
2989 let entry = SupervisorEntry::new(
2990 "waiting-module",
2991 "starting",
2992 true,
2993 false,
2994 SupervisorHealthStatus::Unknown,
2995 );
2996 let old_wire = serde_json::to_value(&entry).unwrap();
2997 assert!(old_wire.get("waiting_for_previous_pid").is_none());
2998 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
2999 assert_eq!(decoded.waiting_for_previous_pid, None);
3000 let entry = entry.with_waiting_for_previous_pid(Some(42));
3001 let wire = serde_json::to_value(&entry).unwrap();
3002 assert_eq!(wire["waiting_for_previous_pid"], 42);
3003 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3004 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3005 }
3006
3007 #[test]
3008 fn diagnostic_string_enums_reject_non_string_bodies() {
3009 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3010 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3011 }
3012
3013 #[test]
3014 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3015 let body = serde_json::json!({
3016 "op": "supervisor.provenance",
3017 "daemon": {
3018 "daemon_build": {},
3019 "daemon_observed": {
3020 "running_image": {
3021 "status": "unavailable",
3022 "reason": "not_running"
3023 }
3024 }
3025 },
3026 "modules": [
3027 {
3028 "module_id": "future",
3029 "module_declared": { "status": "unverifiable" },
3030 "daemon_observed": {
3031 "running_image": {
3032 "status": "unavailable",
3033 "reason": "future_reason"
3034 }
3035 }
3036 },
3037 {
3038 "module_id": "healthy-a",
3039 "module_declared": { "status": "unverifiable" },
3040 "daemon_observed": {
3041 "running_image": {
3042 "status": "match",
3043 "evidence": {
3044 "method": "linux_proc_sha256",
3045 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3046 }
3047 }
3048 }
3049 },
3050 {
3051 "module_id": "healthy-b",
3052 "module_declared": { "status": "unverifiable" },
3053 "daemon_observed": {
3054 "running_image": {
3055 "status": "unavailable",
3056 "reason": "unsupported_platform"
3057 }
3058 }
3059 }
3060 ]
3061 });
3062
3063 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3064 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3065 panic!("decoded wrong response variant");
3066 };
3067 assert_eq!(modules.len(), 3);
3068 assert_eq!(modules[0].module_id, "future");
3069 assert_eq!(
3070 modules[0].daemon_observed.running_image,
3071 RunningImageAgreement::Unavailable {
3072 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3073 }
3074 );
3075 assert_eq!(modules[1].module_id, "healthy-a");
3076 assert_eq!(modules[2].module_id, "healthy-b");
3077 }
3078
3079 #[test]
3080 fn tagged_unknown_values_retain_tag_and_body() {
3081 macro_rules! assert_unknown_round_trip {
3082 ($ty:ident, $field:literal, $value:expr) => {
3083 let value = $value;
3084 let wire = serde_json::to_string(&value).unwrap();
3085 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3086 match decoded {
3087 $ty::Unknown { tag, body } => {
3088 assert_eq!(tag, value[$field].as_str().unwrap());
3089 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3090 }
3091 _ => panic!("decoded known variant"),
3092 }
3093 };
3094 }
3095
3096 assert_unknown_round_trip!(
3097 ModuleDeclaredProvenance,
3098 "status",
3099 serde_json::json!({"status": "future", "build": {"version": 7}})
3100 );
3101 assert_unknown_round_trip!(
3102 RunningImageAgreement,
3103 "status",
3104 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3105 );
3106 assert_unknown_round_trip!(
3107 RunningImageEvidence,
3108 "method",
3109 serde_json::json!({"method": "future", "digest": "abc"})
3110 );
3111 assert_unknown_round_trip!(
3112 SupervisorRouteConsumer,
3113 "kind",
3114 serde_json::json!({"kind": "future", "module_id": "m"})
3115 );
3116 assert_unknown_round_trip!(
3117 StderrCaptureState,
3118 "state",
3119 serde_json::json!({"state": "future", "reason": "because"})
3120 );
3121 assert_unknown_round_trip!(
3122 StderrTailEntry,
3123 "kind",
3124 serde_json::json!({"kind": "future", "text": "line"})
3125 );
3126 assert_unknown_round_trip!(
3127 ChildResourceUsage,
3128 "status",
3129 serde_json::json!({"status": "future", "memory_bytes": 1})
3130 );
3131 }
3132
3133 #[test]
3134 fn child_resource_usage_round_trips_both_known_states() {
3135 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3136 memory_bytes: 0,
3137 memory_kind: ChildMemoryKind::ResidentSet,
3138 swap_bytes: Some(0),
3139 cpu_user_ms: 0,
3140 cpu_system_ms: 0,
3141 });
3142 let wire = serde_json::to_value(&measured).unwrap();
3143 assert_eq!(
3144 wire,
3145 serde_json::json!({
3146 "status": "measured",
3147 "memory_bytes": 0,
3148 "memory_kind": "resident_set",
3149 "swap_bytes": 0,
3150 "cpu_user_ms": 0,
3151 "cpu_system_ms": 0
3152 })
3153 );
3154 assert_eq!(
3155 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3156 measured
3157 );
3158
3159 let unavailable = ChildResourceUsage::Unavailable {
3160 reason: ChildResourceUnavailableReason::NotRunning,
3161 };
3162 let wire = serde_json::to_value(&unavailable).unwrap();
3163 assert_eq!(
3164 wire,
3165 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3166 );
3167 assert_eq!(
3168 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3169 unavailable
3170 );
3171 }
3172
3173 #[test]
3174 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3175 let stamped: StderrTailEntry = serde_json::from_str(
3179 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3180 )
3181 .unwrap();
3182 assert_eq!(
3183 stamped,
3184 StderrTailEntry::Line {
3185 text: "boom".to_string(),
3186 truncated: true,
3187 at_ms: Some(1_789_801_440_685),
3188 }
3189 );
3190 let unstamped: StderrTailEntry =
3191 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3192 assert_eq!(
3193 unstamped,
3194 StderrTailEntry::Line {
3195 text: "boom".to_string(),
3196 truncated: false,
3197 at_ms: None,
3198 }
3199 );
3200 assert_eq!(
3203 serde_json::to_string(&unstamped).unwrap(),
3204 r#"{"kind":"line","text":"boom"}"#
3205 );
3206 assert_eq!(
3207 serde_json::to_value(&stamped).unwrap()["at_ms"],
3208 serde_json::json!(1_789_801_440_685u64)
3209 );
3210 }
3211
3212 #[test]
3213 fn tagged_unknown_values_round_trip_the_original_json() {
3214 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3215 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3216 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3217 }
3218
3219 #[test]
3220 fn tagged_unknown_values_round_trip_trailing_tag() {
3221 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3222 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3223 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3224
3225 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3226 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3227 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3228 }
3229
3230 #[test]
3231 fn tagged_unknown_values_round_trip_middle_tag() {
3232 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3233 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3234 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3235
3236 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3237 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3238 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3239 }
3240
3241 #[test]
3242 fn tagged_unknown_values_round_trip_deep_payload() {
3243 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3244 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3245 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3246
3247 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3248 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3249 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3250 }
3251
3252 #[test]
3253 fn tagged_unknown_values_reject_non_object_bodies() {
3254 for wire in ["42", r#""future""#, "[]"] {
3255 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3256 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3257 }
3258 }
3259
3260 #[test]
3261 fn duplicate_discriminators_reject_without_panicking() {
3262 assert_eq!(
3263 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3264 .unwrap(),
3265 ModuleDeclaredProvenance::Unverifiable
3266 );
3267 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3268 .unwrap()
3269 {
3270 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3271 _ => panic!("future discriminator decoded as a known variant"),
3272 }
3273
3274 let wires = [
3275 r#"{"status":"reported","status":"unverifiable"}"#,
3276 r#"{"status":"unverifiable","status":"reported"}"#,
3277 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3278 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3279 ];
3280
3281 for wire in wires {
3282 let result =
3283 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3284 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3285 assert!(
3286 result.unwrap().is_err(),
3287 "duplicate discriminator decoded: {wire}"
3288 );
3289 }
3290
3291 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3292 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3293 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3294 assert!(
3295 result.unwrap().is_err(),
3296 "duplicate discriminator decoded: {wire}"
3297 );
3298 }
3299
3300 #[test]
3301 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3302 let known_wire =
3303 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3304 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3305 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3306
3307 for wire in [
3308 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3309 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3310 ] {
3311 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3312 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3313 }
3314
3315 for wire in [
3316 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3317 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3318 ] {
3319 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3320 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3321 }
3322
3323 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3324 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3325 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3326
3327 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3328 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3329 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3330 }
3331
3332 #[test]
3333 fn tagged_unknown_member_does_not_discard_known_siblings() {
3334 let body = serde_json::json!({
3335 "modules": [{
3336 "module_id": "target",
3337 "routes": [
3338 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3339 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3340 ]
3341 }]
3342 });
3343 let decoded: ClientControlResponse = serde_json::from_value(
3344 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3345 )
3346 .unwrap();
3347 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3348 panic!("decoded wrong response variant");
3349 };
3350 assert_eq!(modules[0].routes.len(), 2);
3351 assert_eq!(
3352 modules[0].routes[1].consumer,
3353 SupervisorRouteConsumer::Direct { connection_id: 7 }
3354 );
3355 }
3356}
3357
3358#[cfg(test)]
3359mod launch_nonce_redaction_tests {
3360 use super::*;
3361
3362 const NONCE: &str = "nonce-f00dfeed1234abcd";
3363
3364 fn identity() -> ConsumerIdentity {
3365 ConsumerIdentity {
3366 module_id: "wernicke".to_string(),
3367 launch_nonce: NONCE.to_string(),
3368 }
3369 }
3370
3371 #[test]
3372 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3373 let printed = format!("{:?}", identity());
3374 assert!(printed.contains("wernicke"), "{printed}");
3375 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3376 }
3377
3378 #[test]
3379 fn route_open_request_debug_never_prints_the_nonce() {
3380 let request = ClientControlRequest::RouteOpen {
3381 target: subc_protocol::RouteTarget::ToolProvider {
3382 module_id: "broca".to_string(),
3383 },
3384 identity: subc_protocol::BindIdentity::new(
3385 PathBuf::from("/tmp/project"),
3386 "test".to_string(),
3387 "session".to_string(),
3388 ),
3389 consumer_identity: Some(identity()),
3390 consumer_capabilities: None,
3391 role_versions: None,
3392 admission_facts: None,
3393 scope: None,
3394 };
3395 let printed = format!("{request:?}");
3396 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3397 }
3398}