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::*;
93mod tree;
94pub use tree::*;
95
96#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
98pub struct ConsumerIdentity {
99 pub module_id: String,
100 pub launch_nonce: String,
101}
102
103impl std::fmt::Debug for ConsumerIdentity {
108 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 f.debug_struct("ConsumerIdentity")
110 .field("module_id", &self.module_id)
111 .field(
112 "launch_nonce",
113 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
114 )
115 .finish()
116 }
117}
118
119pub mod ops {
130 pub const SERVER: &str = "server.";
131 pub const CATALOG: &str = "catalog.";
132 pub const ROUTE: &str = "route.";
133 pub const SUPERVISOR: &str = "supervisor.";
134 pub const CONFIG: &str = "config.";
135
136 pub const SERVER_DESCRIBE: &str = "server.describe";
137 pub const DAEMON_SHUTDOWN_INTENT: &str = "daemon.shutdown_intent";
138 pub const CATALOG_LIST: &str = "catalog.list";
139 pub const ROUTE_OPEN: &str = "route.open";
140 pub const ROUTE_POLL: &str = "route.poll";
141 pub const ROUTE_CLOSING: &str = "route.closing";
142 pub const ROUTE_CLOSED: &str = "route.closed";
143 pub const SUPERVISOR_LIST: &str = "supervisor.list";
144 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
145 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
146 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
147 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
148 pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
149 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
150 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
151 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
152 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
153 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
154 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
155 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
156 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
157 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
158 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
159 pub const ACTIVITY_RECORD: &str = "activity.record";
160 pub const ACTIVITY_QUERY: &str = "activity.query";
161 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
162 pub const APP_OPEN: &str = "app.open";
163 pub const CONNECTION_DESCRIBE: &str = "connection.describe";
164}
165
166#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
168#[serde(tag = "op")]
169#[allow(clippy::large_enum_variant)]
172pub enum ClientControlRequest {
173 #[serde(rename = "daemon.shutdown_intent")]
176 DaemonShutdownIntent {
177 #[serde(default)]
178 intent: serde_json::Value,
179 },
180 #[serde(rename = "server.describe")]
181 ServerDescribe {},
182 #[serde(rename = "catalog.list")]
183 CatalogList {
184 #[serde(default)]
189 module_id: Option<String>,
190 },
191 #[serde(rename = "route.open")]
192 RouteOpen {
193 target: RouteTarget,
194 identity: BindIdentity,
195 #[serde(default, skip_serializing_if = "Option::is_none")]
204 consumer_identity: Option<ConsumerIdentity>,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
213 consumer_capabilities: Option<Vec<String>>,
214 #[serde(default, skip_serializing_if = "Option::is_none")]
225 role_versions: Option<BTreeMap<String, String>>,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
230 busy_refusals: Option<bool>,
231 #[serde(default, skip_serializing_if = "Option::is_none")]
233 admission_facts: Option<serde_json::Value>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
241 scope: Option<ScopeSelector>,
242 },
243 #[serde(rename = "route.poll")]
244 RoutePoll {
245 route_channel: u16,
246 route_epoch: u32,
247 kind: PollKind,
248 },
249 #[serde(rename = "supervisor.list")]
250 SupervisorList {},
251 #[serde(rename = "supervisor.spawn_snapshot")]
253 SupervisorSpawnSnapshot {},
254 #[serde(rename = "supervisor.spawn_subscribe")]
270 SupervisorSpawnSubscribe {
271 #[serde(default, skip_serializing_if = "Option::is_none")]
272 since: Option<SpawnCursor>,
273 },
274 #[serde(rename = "supervisor.restart")]
275 SupervisorRestart {
276 module_id: String,
277 #[serde(default, skip_serializing_if = "Option::is_none")]
287 drain_timeout_ms: Option<u64>,
288 },
289 #[serde(rename = "supervisor.swap")]
304 SupervisorSwap {
305 module_id: String,
306 #[serde(default, skip_serializing_if = "Option::is_none")]
309 ready_timeout_ms: Option<u64>,
310 },
311 #[serde(rename = "supervisor.reload")]
312 SupervisorReload { module_id: String },
313 #[serde(rename = "supervisor.rescan")]
314 SupervisorRescan {
315 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
335 preview: bool,
336 },
337 #[serde(rename = "supervisor.rescan_checked")]
361 SupervisorRescanChecked {
362 preview: bool,
363 #[serde(default, skip_serializing_if = "Option::is_none")]
364 candidate: Option<String>,
365 #[serde(default, skip_serializing_if = "Option::is_none")]
366 expect: Option<RescanExpect>,
367 },
368 #[serde(rename = "supervisor.release_reserved")]
372 SupervisorReleaseReserved { module_id: String },
373 #[serde(rename = "supervisor.set_enabled")]
374 SupervisorSetEnabled { module_id: String, enabled: bool },
375 #[serde(rename = "supervisor.health_probe")]
376 SupervisorHealthProbe { module_id: String },
377 #[serde(rename = "supervisor.health")]
378 SupervisorHealth {},
379 #[serde(rename = "supervisor.routes")]
392 SupervisorRoutes {
393 #[serde(default, skip_serializing_if = "Option::is_none")]
394 module_id: Option<String>,
395 },
396 #[serde(rename = "supervisor.provenance")]
399 SupervisorProvenance {
400 #[serde(default, skip_serializing_if = "Option::is_none")]
401 module_id: Option<String>,
402 },
403 #[serde(rename = "supervisor.stderr_tail")]
411 SupervisorStderrTail {
412 module_id: String,
413 #[serde(default, skip_serializing_if = "Option::is_none")]
414 max_lines: Option<u32>,
415 #[serde(default, skip_serializing_if = "Option::is_none")]
416 max_bytes: Option<u32>,
417 },
418 #[serde(rename = "supervisor.terminals")]
431 SupervisorTerminals { module_id: String },
432}
433
434#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
436#[serde(tag = "op")]
437pub enum ClientControlResponse {
438 #[serde(rename = "daemon.shutdown_intent")]
439 DaemonShutdownIntent { intent: String, expires_at_ms: u64 },
440 #[serde(rename = "server.describe")]
441 ServerDescribe {
442 protocol_ver: u8,
443 subc_ops: Vec<String>,
444 capabilities: Vec<String>,
445 connected_clients: u64,
446 #[serde(default, skip_serializing_if = "Option::is_none")]
447 counters: Option<serde_json::Value>,
448 #[serde(default, skip_serializing_if = "Option::is_none")]
455 build_git_sha: Option<String>,
456 #[serde(default, skip_serializing_if = "Option::is_none")]
462 build_lock_digest: Option<String>,
463 #[serde(default, skip_serializing_if = "Vec::is_empty")]
467 capability_requirements: Vec<CapabilityRequirementStatus>,
468 #[serde(default, skip_serializing_if = "Option::is_none")]
473 machine_id: Option<String>,
474 #[serde(default, skip_serializing_if = "Option::is_none")]
483 config_path: Option<PathBuf>,
484 },
485 #[serde(rename = "catalog.list")]
486 CatalogList {
487 generation: u64,
488 modules: Vec<CatalogEntry>,
489 subc_ops: Vec<String>,
490 },
491 #[serde(rename = "route.open")]
492 RouteOpen {
493 route_channel: u16,
494 route_epoch: u32,
495 #[serde(default, skip_serializing_if = "Option::is_none")]
497 request_window: Option<usize>,
498 #[serde(default, skip_serializing_if = "Option::is_none")]
500 watch_window: Option<usize>,
501 },
502 #[serde(rename = "route.poll")]
503 RoutePoll {
504 route_channel: u16,
505 route_epoch: u32,
506 status: Option<String>,
507 live: Option<bool>,
508 },
509 #[serde(rename = "supervisor.list")]
510 SupervisorList {
511 generation: u64,
512 modules: Vec<SupervisorEntry>,
513 #[serde(default, skip_serializing_if = "Option::is_none")]
514 daemon: Option<DaemonResources>,
515 #[serde(default, skip_serializing_if = "Option::is_none")]
516 agent_commands: Option<Vec<AgentCommandResources>>,
517 },
518 #[serde(rename = "supervisor.spawn_snapshot")]
519 SupervisorSpawnSnapshot {
520 #[serde(flatten)]
521 snapshot: SpawnSnapshot,
522 },
523 #[serde(rename = "supervisor.ack")]
524 SupervisorAck { module_id: String, applied: bool },
525 #[serde(rename = "supervisor.rescan")]
526 SupervisorRescan {
527 #[serde(flatten)]
528 result: SupervisorRescanResult,
529 },
530 #[serde(rename = "supervisor.health_probe")]
531 SupervisorHealthProbe {
532 module_id: String,
533 status: HealthStatus,
534 #[serde(default, skip_serializing_if = "Option::is_none")]
535 detail: Option<String>,
536 #[serde(default, skip_serializing_if = "Option::is_none")]
537 metrics: Option<serde_json::Value>,
538 },
539 #[serde(rename = "supervisor.health")]
540 SupervisorHealth {
541 generation: u64,
542 modules: Vec<SupervisorHealthEntry>,
543 },
544 #[serde(rename = "supervisor.routes")]
545 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
546 #[serde(rename = "supervisor.provenance")]
547 SupervisorProvenance {
548 daemon: SupervisorDaemonProvenance,
549 modules: Vec<SupervisorModuleProvenance>,
550 },
551 #[serde(rename = "supervisor.stderr_tail")]
552 SupervisorStderrTail {
553 module_id: String,
554 #[serde(flatten)]
555 tail: StderrTail,
556 },
557 #[serde(rename = "supervisor.terminals")]
558 SupervisorTerminals {
559 module_id: String,
560 #[serde(flatten)]
561 terminals: TerminalHistory,
562 },
563}
564
565#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
570#[serde(tag = "op")]
571pub enum ClientControlPush {
572 #[serde(rename = "route.closing")]
573 RouteClosing {
574 module_id: String,
575 #[serde(default)]
578 channels: Vec<u16>,
579 reason: RouteCloseReason,
580 },
581 #[serde(rename = "route.closed")]
582 RouteClosed {
583 module_id: String,
584 #[serde(default)]
587 channels: Vec<u16>,
588 reason: RouteCloseReason,
589 drained: bool,
591 abandoned: u32,
594 #[serde(default)]
596 excluded_subscriptions: u32,
597 #[serde(default, skip_serializing_if = "Option::is_none")]
603 terminal: Option<bool>,
604 },
605}
606
607#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
609pub struct SpawnCursor {
610 pub daemon_incarnation: String,
611 pub seq: u64,
612}
613
614#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
616pub struct LiveSpawn {
617 pub module_id: String,
618 pub spawn_generation: u64,
619 pub pid: u32,
620 pub spawned_at_ms: u64,
621}
622
623#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
625pub struct SpawnSnapshot {
626 pub cursor: SpawnCursor,
627 pub ring_bound: u64,
629 pub live: Vec<LiveSpawn>,
630}
631
632#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
634#[serde(rename_all = "snake_case")]
635pub enum SpawnEventKind {
636 Spawned,
637 Exited,
638}
639
640#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
646pub struct SpawnEvent {
647 pub cursor: SpawnCursor,
648 pub kind: SpawnEventKind,
649 pub module_id: String,
650 pub spawn_generation: u64,
651 pub pid: u32,
652 #[serde(default, skip_serializing_if = "Option::is_none")]
653 pub exit_code: Option<i32>,
654 #[serde(default, skip_serializing_if = "Option::is_none")]
655 pub exit_signal: Option<i32>,
656}
657
658#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
660pub struct StderrTail {
661 pub capture: StderrCaptureState,
662 pub entries: Vec<StderrTailEntry>,
663 #[serde(default, skip_serializing_if = "is_zero_u64")]
672 pub dropped_lines: u64,
673}
674
675#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
677pub struct SupervisorRouteModule {
678 pub module_id: String,
679 pub routes: Vec<SupervisorRoute>,
680}
681
682#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
684pub struct SupervisorRoute {
685 pub consumer: SupervisorRouteConsumer,
686 pub age_ms: u64,
688 pub draining: bool,
691 #[serde(default, skip_serializing_if = "Option::is_none")]
697 pub drain_reason: Option<RouteCloseReason>,
698}
699
700#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
702pub struct SupervisorModuleProvenance {
703 pub module_id: String,
704 pub module_declared: ModuleDeclaredProvenance,
705 pub daemon_observed: SupervisorObservedProcess,
706}
707
708#[derive(Debug, Clone, PartialEq)]
710pub enum ModuleDeclaredProvenance {
711 Reported {
712 build: ManifestProvenance,
713 },
714 Unverifiable,
715 Unknown {
718 tag: String,
719 body: OrderedJsonObject,
720 },
721}
722
723#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
728pub struct SupervisorObservedProcess {
729 #[serde(default, skip_serializing_if = "Option::is_none")]
735 pub launch_nonce_source: Option<String>,
736 #[serde(default, skip_serializing_if = "Option::is_none")]
737 pub pid: Option<u32>,
738 #[serde(default, skip_serializing_if = "Option::is_none")]
739 pub spawned_at_ms: Option<u64>,
740 #[serde(default, skip_serializing_if = "Option::is_none")]
741 pub spawned_from: Option<PathBuf>,
742 pub running_image: RunningImageAgreement,
743}
744
745#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
762#[non_exhaustive]
763pub struct PendingReloadVerdict {
764 pub path: ReloadPathAgreement,
765 pub image: RunningImageAgreement,
766 #[serde(default, skip_serializing_if = "Option::is_none")]
767 pub spec: Option<LaunchSpecAgreement>,
768}
769
770impl PendingReloadVerdict {
771 #[must_use]
773 pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
774 Self {
775 path,
776 image,
777 spec: None,
778 }
779 }
780
781 #[must_use]
783 pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
784 self.spec = spec;
785 self
786 }
787}
788
789#[cfg(test)]
790mod launch_spec_wire_tests {
791 use super::*;
792
793 #[test]
794 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
795 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
796 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
797 assert_eq!(parsed.spec, None);
798 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
799 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
800 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
801 assert!(
802 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
803 );
804 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
805 let unavailable = LaunchSpecAgreement::Unavailable {
806 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
807 };
808 let encoded = serde_json::to_string(&unavailable).unwrap();
809 assert_eq!(
810 encoded,
811 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
812 );
813 assert_eq!(
814 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
815 unavailable
816 );
817 }
818}
819
820#[derive(Debug, Clone, PartialEq)]
823pub enum LaunchSpecAgreement {
824 Match,
825 Mismatch,
826 Unavailable {
827 reason: LaunchSpecUnavailableReason,
828 },
829 Unknown {
830 tag: String,
831 body: OrderedJsonObject,
832 },
833}
834
835open_string_enum! {
836 LaunchSpecUnavailableReason {
837 NotRunning => "not_running",
838 SpawnedSpecUnavailable => "spawned_spec_unavailable",
839 }
840}
841
842#[derive(Debug, Clone, PartialEq)]
844pub enum ReloadPathAgreement {
845 Match,
846 Mismatch {
847 configured: PathBuf,
848 spawned_from: PathBuf,
849 },
850 Unavailable {
851 reason: ReloadPathUnavailableReason,
852 },
853 Unknown {
854 tag: String,
855 body: OrderedJsonObject,
856 },
857}
858
859open_string_enum! {
860 ReloadPathUnavailableReason {
862 NotRunning => "not_running",
863 SpawnedPathUnavailable => "spawned_path_unavailable",
864 }
865}
866
867#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
869pub struct SupervisorDaemonProvenance {
870 pub daemon_build: DaemonBuildProvenance,
871 pub daemon_observed: DaemonObservedProcess,
872}
873
874#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
876pub struct DaemonBuildProvenance {
877 #[serde(default, skip_serializing_if = "Option::is_none")]
878 pub build_git_sha: Option<String>,
879 #[serde(default, skip_serializing_if = "Option::is_none")]
880 pub build_lock_digest: Option<String>,
881}
882
883#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
885pub struct DaemonObservedProcess {
886 #[serde(default, skip_serializing_if = "Option::is_none")]
887 pub pid: Option<u32>,
888 #[serde(default, skip_serializing_if = "Option::is_none")]
893 pub started_at_ms: Option<u64>,
894 pub running_image: RunningImageAgreement,
895}
896
897#[derive(Debug, Clone, PartialEq)]
899pub enum RunningImageAgreement {
900 Match {
901 evidence: RunningImageEvidence,
902 },
903 Mismatch {
904 running: RunningImageEvidence,
905 disk: RunningImageEvidence,
906 },
907 Unavailable {
908 reason: RunningImageUnavailableReason,
909 },
910 Unknown {
913 tag: String,
914 body: OrderedJsonObject,
915 },
916}
917
918#[derive(Debug, Clone, PartialEq)]
920pub enum RunningImageEvidence {
921 LinuxProcSha256 {
922 digest: String,
923 },
924 MacosSpawnInode {
925 device: u64,
926 inode: u64,
927 },
928 WindowsSpawnFileId {
930 volume_serial_number: u64,
931 file_id: [u8; 16],
932 },
933 Unknown {
936 tag: String,
937 body: OrderedJsonObject,
938 },
939}
940
941open_string_enum! {
942 RunningImageUnavailableReason {
944 NotRunning => "not_running",
945 NotYetMeasured => "not_yet_measured",
946 UnsupportedPlatform => "unsupported_platform",
947 RunningExecutableUnreadable => "running_executable_unreadable",
948 RunningExecutablePermissionDenied => "running_executable_permission_denied",
949 ProcessHidden => "process_hidden",
950 SpawnedPathUnreadable => "spawned_path_unreadable",
951 HashFailed => "hash_failed",
952 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
953 }
954}
955
956#[derive(Debug, Clone, PartialEq)]
962pub enum SupervisorRouteConsumer {
963 Reserved {
964 module_id: String,
965 },
966 Direct {
967 connection_id: u64,
968 },
969 Unknown {
972 tag: String,
973 body: OrderedJsonObject,
974 },
975}
976
977#[derive(Debug, Clone, PartialEq)]
984pub enum StderrCaptureState {
985 Captured,
988 Incomplete { reason: String },
990 NotCaptured { reason: String },
992 Unknown {
995 tag: String,
996 body: OrderedJsonObject,
997 },
998}
999
1000#[derive(Debug, Clone, PartialEq)]
1001pub enum StderrTailEntry {
1002 Line {
1003 text: String,
1004 truncated: bool,
1009 at_ms: Option<u64>,
1013 },
1014 ProcessStart,
1019 Unknown {
1022 tag: String,
1023 body: OrderedJsonObject,
1024 },
1025}
1026
1027#[derive(Debug, Serialize, Deserialize)]
1028#[serde(tag = "status", rename_all = "snake_case")]
1029enum ModuleDeclaredProvenanceWire {
1030 Reported { build: ManifestProvenance },
1031 Unverifiable,
1032}
1033
1034#[derive(Debug, Serialize, Deserialize)]
1035#[serde(tag = "status", rename_all = "snake_case")]
1036enum RunningImageAgreementWire {
1037 Match {
1038 evidence: RunningImageEvidence,
1039 },
1040 Mismatch {
1041 running: RunningImageEvidence,
1042 disk: RunningImageEvidence,
1043 },
1044 Unavailable {
1045 reason: RunningImageUnavailableReason,
1046 },
1047}
1048
1049#[derive(Debug, Serialize, Deserialize)]
1050#[serde(tag = "status", rename_all = "snake_case")]
1051enum ReloadPathAgreementWire {
1052 Match,
1053 Mismatch {
1054 configured: PathBuf,
1055 spawned_from: PathBuf,
1056 },
1057 Unavailable {
1058 reason: ReloadPathUnavailableReason,
1059 },
1060}
1061
1062#[derive(Debug, Serialize, Deserialize)]
1063#[serde(tag = "status", rename_all = "snake_case")]
1064enum LaunchSpecAgreementWire {
1065 Match,
1066 Mismatch,
1067 Unavailable { reason: LaunchSpecUnavailableReason },
1068}
1069
1070#[derive(Debug, Serialize, Deserialize)]
1071#[serde(tag = "method", rename_all = "snake_case")]
1072enum RunningImageEvidenceWire {
1073 LinuxProcSha256 {
1074 digest: String,
1075 },
1076 MacosSpawnInode {
1077 device: u64,
1078 inode: u64,
1079 },
1080 WindowsSpawnFileId {
1081 volume_serial_number: u64,
1082 file_id: [u8; 16],
1083 },
1084}
1085
1086#[derive(Debug, Serialize, Deserialize)]
1087#[serde(tag = "kind", rename_all = "snake_case")]
1088enum SupervisorRouteConsumerWire {
1089 Reserved { module_id: String },
1090 Direct { connection_id: u64 },
1091}
1092
1093#[derive(Debug, Serialize, Deserialize)]
1094#[serde(tag = "state", rename_all = "snake_case")]
1095enum StderrCaptureStateWire {
1096 Captured,
1097 Incomplete { reason: String },
1098 NotCaptured { reason: String },
1099}
1100
1101#[derive(Debug, Serialize, Deserialize)]
1102#[serde(tag = "status", rename_all = "snake_case")]
1103enum ChildResourceUsageWire {
1104 Measured(ChildResourceReading),
1105 Unavailable {
1106 reason: ChildResourceUnavailableReason,
1107 },
1108}
1109
1110#[derive(Debug, Serialize, Deserialize)]
1111#[serde(tag = "kind", rename_all = "snake_case")]
1112enum StderrTailEntryWire {
1113 Line {
1114 text: String,
1115 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1116 truncated: bool,
1117 #[serde(default, skip_serializing_if = "Option::is_none")]
1120 at_ms: Option<u64>,
1121 },
1122 ProcessStart,
1123}
1124
1125#[derive(Debug, Clone, PartialEq)]
1127pub enum OrderedJsonValue {
1128 Null,
1129 Bool(bool),
1130 Number(serde_json::Number),
1131 String(String),
1132 Array(Vec<Self>),
1133 Object(OrderedJsonObject),
1134}
1135
1136#[derive(Debug, Clone, PartialEq)]
1138pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1139
1140impl OrderedJsonObject {
1141 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1143 &self.0
1144 }
1145
1146 fn into_value(self) -> serde_json::Value {
1147 serde_json::Value::Object(
1148 self.0
1149 .into_iter()
1150 .map(|(key, value)| (key, value.into_value()))
1151 .collect(),
1152 )
1153 }
1154}
1155
1156impl OrderedJsonValue {
1157 fn into_value(self) -> serde_json::Value {
1158 match self {
1159 Self::Null => serde_json::Value::Null,
1160 Self::Bool(value) => serde_json::Value::Bool(value),
1161 Self::Number(value) => serde_json::Value::Number(value),
1162 Self::String(value) => serde_json::Value::String(value),
1163 Self::Array(values) => {
1164 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1165 }
1166 Self::Object(value) => value.into_value(),
1167 }
1168 }
1169}
1170
1171impl Serialize for OrderedJsonValue {
1172 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1173 where
1174 S: Serializer,
1175 {
1176 match self {
1177 Self::Null => serializer.serialize_unit(),
1178 Self::Bool(value) => serializer.serialize_bool(*value),
1179 Self::Number(value) => value.serialize(serializer),
1180 Self::String(value) => serializer.serialize_str(value),
1181 Self::Array(values) => values.serialize(serializer),
1182 Self::Object(value) => value.serialize(serializer),
1183 }
1184 }
1185}
1186
1187impl<'de> Deserialize<'de> for OrderedJsonValue {
1188 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1189 where
1190 D: Deserializer<'de>,
1191 {
1192 struct OrderedValueVisitor;
1193
1194 impl<'de> Visitor<'de> for OrderedValueVisitor {
1195 type Value = OrderedJsonValue;
1196
1197 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1198 formatter.write_str("a JSON value with ordered object members")
1199 }
1200
1201 fn visit_unit<E>(self) -> Result<Self::Value, E>
1202 where
1203 E: serde::de::Error,
1204 {
1205 Ok(OrderedJsonValue::Null)
1206 }
1207
1208 fn visit_none<E>(self) -> Result<Self::Value, E>
1209 where
1210 E: serde::de::Error,
1211 {
1212 Ok(OrderedJsonValue::Null)
1213 }
1214
1215 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1216 where
1217 D: Deserializer<'de>,
1218 {
1219 OrderedJsonValue::deserialize(deserializer)
1220 }
1221
1222 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1223 where
1224 E: serde::de::Error,
1225 {
1226 Ok(OrderedJsonValue::Bool(value))
1227 }
1228
1229 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1230 where
1231 E: serde::de::Error,
1232 {
1233 Ok(OrderedJsonValue::Number(value.into()))
1234 }
1235
1236 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1237 where
1238 E: serde::de::Error,
1239 {
1240 Ok(OrderedJsonValue::Number(value.into()))
1241 }
1242
1243 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1244 where
1245 E: serde::de::Error,
1246 {
1247 serde_json::Number::from_f64(value)
1248 .map(OrderedJsonValue::Number)
1249 .ok_or_else(|| E::custom("non-finite JSON number"))
1250 }
1251
1252 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1253 where
1254 E: serde::de::Error,
1255 {
1256 Ok(OrderedJsonValue::String(value.to_owned()))
1257 }
1258
1259 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1260 where
1261 E: serde::de::Error,
1262 {
1263 Ok(OrderedJsonValue::String(value))
1264 }
1265
1266 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1267 where
1268 A: SeqAccess<'de>,
1269 {
1270 let mut values = Vec::new();
1271 while let Some(value) = sequence.next_element()? {
1272 values.push(value);
1273 }
1274 Ok(OrderedJsonValue::Array(values))
1275 }
1276
1277 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1278 where
1279 A: MapAccess<'de>,
1280 {
1281 let mut entries = Vec::new();
1282 while let Some((key, value)) = map.next_entry()? {
1283 entries.push((key, value));
1284 }
1285 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1286 }
1287 }
1288
1289 deserializer.deserialize_any(OrderedValueVisitor)
1290 }
1291}
1292
1293impl Serialize for OrderedJsonObject {
1294 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1295 where
1296 S: Serializer,
1297 {
1298 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1299 for (key, value) in &self.0 {
1300 map.serialize_entry(key, value)?;
1301 }
1302 map.end()
1303 }
1304}
1305
1306impl<'de> Deserialize<'de> for OrderedJsonObject {
1307 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1308 where
1309 D: Deserializer<'de>,
1310 {
1311 struct OrderedObjectVisitor;
1312
1313 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1314 type Value = OrderedJsonObject;
1315
1316 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1317 formatter.write_str("an object with ordered JSON members")
1318 }
1319
1320 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1321 where
1322 A: MapAccess<'de>,
1323 {
1324 let mut entries = Vec::new();
1325 while let Some((key, value)) = map.next_entry()? {
1326 entries.push((key, value));
1327 }
1328 Ok(OrderedJsonObject(entries))
1329 }
1330 }
1331
1332 deserializer.deserialize_map(OrderedObjectVisitor)
1333 }
1334}
1335
1336fn read_tagged<'de, D>(
1337 deserializer: D,
1338 field: &'static str,
1339) -> Result<(String, OrderedJsonObject), D::Error>
1340where
1341 D: Deserializer<'de>,
1342{
1343 let body = OrderedJsonObject::deserialize(deserializer)?;
1344 let mut tag = None;
1345 for (key, value) in body.as_entries() {
1346 if key != field {
1347 continue;
1348 }
1349 if tag.is_some() {
1350 return Err(D::Error::custom(format!(
1351 "tagged object has duplicate `{field}` field"
1352 )));
1353 }
1354 let OrderedJsonValue::String(value) = value else {
1355 return Err(D::Error::custom(format!(
1356 "tagged object has no string `{field}` field"
1357 )));
1358 };
1359 tag = Some(value);
1360 }
1361 let Some(tag) = tag else {
1362 return Err(D::Error::custom(format!(
1363 "tagged object has no string `{field}` field"
1364 )));
1365 };
1366 Ok((tag.to_string(), body))
1367}
1368
1369fn read_ordered_tagged(
1370 value: OrderedJsonValue,
1371 field: &'static str,
1372) -> Result<(String, OrderedJsonObject), String> {
1373 let OrderedJsonValue::Object(body) = value else {
1374 return Err(format!("expected tagged object with `{field}` field"));
1375 };
1376 let mut tag = None;
1377 for (key, value) in body.as_entries() {
1378 if key != field {
1379 continue;
1380 }
1381 if tag.is_some() {
1382 return Err(format!("tagged object has duplicate `{field}` field"));
1383 }
1384 let OrderedJsonValue::String(value) = value else {
1385 return Err(format!("tagged object has no string `{field}` field"));
1386 };
1387 tag = Some(value);
1388 }
1389 let Some(tag) = tag else {
1390 return Err(format!("tagged object has no string `{field}` field"));
1391 };
1392 Ok((tag.to_string(), body))
1393}
1394
1395fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1396 body.as_entries()
1397 .iter()
1398 .find_map(|(key, value)| (key == field).then_some(value))
1399}
1400
1401fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1402 match ordered_field(body, field) {
1403 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1404 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1405 None => Err(format!("tagged object has no `{field}` field")),
1406 }
1407}
1408
1409fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1410 let (tag, body) = read_ordered_tagged(value, "method")?;
1411 match tag.as_str() {
1412 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1413 digest: ordered_string(&body, "digest")?,
1414 }),
1415 "macos_spawn_inode" => {
1416 let device = ordered_field(&body, "device")
1417 .and_then(|value| match value {
1418 OrderedJsonValue::Number(number) => number.as_u64(),
1419 _ => None,
1420 })
1421 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1422 let inode = ordered_field(&body, "inode")
1423 .and_then(|value| match value {
1424 OrderedJsonValue::Number(number) => number.as_u64(),
1425 _ => None,
1426 })
1427 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1428 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1429 }
1430 "windows_spawn_file_id" => {
1431 let wire: RunningImageEvidenceWire = serde_json::from_value(
1432 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1433 )
1434 .map_err(|error| error.to_string())?;
1435 match wire {
1436 RunningImageEvidenceWire::WindowsSpawnFileId {
1437 volume_serial_number,
1438 file_id,
1439 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1440 volume_serial_number,
1441 file_id,
1442 }),
1443 _ => unreachable!(),
1444 }
1445 }
1446 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1447 }
1448}
1449
1450impl Serialize for ModuleDeclaredProvenance {
1451 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1452 where
1453 S: Serializer,
1454 {
1455 match self {
1456 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1457 build: build.clone(),
1458 }
1459 .serialize(serializer),
1460 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1461 Self::Unknown { body, .. } => body.serialize(serializer),
1462 }
1463 }
1464}
1465
1466impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1467 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1468 where
1469 D: serde::Deserializer<'de>,
1470 {
1471 let (tag, value) = read_tagged(deserializer, "status")?;
1472 match tag.as_str() {
1473 "reported" => match serde_json::from_value(value.into_value())
1474 .map_err(D::Error::custom)?
1475 {
1476 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1477 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1478 },
1479 "unverifiable" => {
1480 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1481 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1482 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1483 }
1484 }
1485 _ => Ok(Self::Unknown { tag, body: value }),
1486 }
1487 }
1488}
1489
1490impl Serialize for RunningImageAgreement {
1491 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1492 where
1493 S: Serializer,
1494 {
1495 match self {
1496 Self::Match { evidence } => RunningImageAgreementWire::Match {
1497 evidence: evidence.clone(),
1498 }
1499 .serialize(serializer),
1500 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1501 running: running.clone(),
1502 disk: disk.clone(),
1503 }
1504 .serialize(serializer),
1505 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1506 reason: reason.clone(),
1507 }
1508 .serialize(serializer),
1509 Self::Unknown { body, .. } => body.serialize(serializer),
1510 }
1511 }
1512}
1513
1514impl Serialize for ReloadPathAgreement {
1515 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1516 where
1517 S: Serializer,
1518 {
1519 match self {
1520 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1521 Self::Mismatch {
1522 configured,
1523 spawned_from,
1524 } => ReloadPathAgreementWire::Mismatch {
1525 configured: configured.clone(),
1526 spawned_from: spawned_from.clone(),
1527 }
1528 .serialize(serializer),
1529 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1530 reason: reason.clone(),
1531 }
1532 .serialize(serializer),
1533 Self::Unknown { body, .. } => body.serialize(serializer),
1534 }
1535 }
1536}
1537
1538impl Serialize for LaunchSpecAgreement {
1539 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1540 where
1541 S: Serializer,
1542 {
1543 match self {
1544 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1545 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1546 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1547 reason: reason.clone(),
1548 }
1549 .serialize(serializer),
1550 Self::Unknown { body, .. } => body.serialize(serializer),
1551 }
1552 }
1553}
1554
1555impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1556 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1557 where
1558 D: Deserializer<'de>,
1559 {
1560 let (tag, body) = read_tagged(deserializer, "status")?;
1561 match tag.as_str() {
1562 "match" => Ok(Self::Match),
1563 "mismatch" => Ok(Self::Mismatch),
1564 "unavailable" => match serde_json::from_value(body.into_value())
1565 .map_err(D::Error::custom)?
1566 {
1567 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1568 _ => unreachable!(),
1569 },
1570 _ => Ok(Self::Unknown { tag, body }),
1571 }
1572 }
1573}
1574
1575impl<'de> Deserialize<'de> for ReloadPathAgreement {
1576 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1577 where
1578 D: Deserializer<'de>,
1579 {
1580 let (tag, body) = read_tagged(deserializer, "status")?;
1581 match tag.as_str() {
1582 "match" => Ok(Self::Match),
1583 "mismatch" => {
1584 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1585 ReloadPathAgreementWire::Mismatch {
1586 configured,
1587 spawned_from,
1588 } => Ok(Self::Mismatch {
1589 configured,
1590 spawned_from,
1591 }),
1592 _ => unreachable!(),
1593 }
1594 }
1595 "unavailable" => match serde_json::from_value(body.into_value())
1596 .map_err(D::Error::custom)?
1597 {
1598 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1599 _ => unreachable!(),
1600 },
1601 _ => Ok(Self::Unknown { tag, body }),
1602 }
1603 }
1604}
1605
1606impl<'de> Deserialize<'de> for RunningImageAgreement {
1607 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1608 where
1609 D: serde::Deserializer<'de>,
1610 {
1611 let (tag, value) = read_tagged(deserializer, "status")?;
1612 match tag.as_str() {
1613 "match" => Ok(Self::Match {
1614 evidence: decode_running_image_evidence(
1615 ordered_field(&value, "evidence")
1616 .cloned()
1617 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1618 )
1619 .map_err(D::Error::custom)?,
1620 }),
1621 "mismatch" => Ok(Self::Mismatch {
1622 running: decode_running_image_evidence(
1623 ordered_field(&value, "running")
1624 .cloned()
1625 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1626 )
1627 .map_err(D::Error::custom)?,
1628 disk: decode_running_image_evidence(
1629 ordered_field(&value, "disk")
1630 .cloned()
1631 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1632 )
1633 .map_err(D::Error::custom)?,
1634 }),
1635 "unavailable" => Ok(Self::Unavailable {
1636 reason: serde_json::from_value(
1637 ordered_field(&value, "reason")
1638 .cloned()
1639 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1640 .into_value(),
1641 )
1642 .map_err(D::Error::custom)?,
1643 }),
1644 _ => Ok(Self::Unknown { tag, body: value }),
1645 }
1646 }
1647}
1648
1649impl Serialize for ChildResourceUsage {
1650 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1651 where
1652 S: Serializer,
1653 {
1654 match self {
1655 Self::Measured(reading) => {
1656 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1657 }
1658 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1659 reason: reason.clone(),
1660 }
1661 .serialize(serializer),
1662 Self::Unknown { body, .. } => body.serialize(serializer),
1663 }
1664 }
1665}
1666
1667impl<'de> Deserialize<'de> for ChildResourceUsage {
1668 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1669 where
1670 D: Deserializer<'de>,
1671 {
1672 let (tag, body) = read_tagged(deserializer, "status")?;
1673 match tag.as_str() {
1674 "measured" | "unavailable" => {
1675 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1676 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1677 ChildResourceUsageWire::Unavailable { reason } => {
1678 Ok(Self::Unavailable { reason })
1679 }
1680 }
1681 }
1682 _ => Ok(Self::Unknown { tag, body }),
1683 }
1684 }
1685}
1686
1687impl Serialize for RunningImageEvidence {
1688 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1689 where
1690 S: Serializer,
1691 {
1692 match self {
1693 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1694 digest: digest.clone(),
1695 }
1696 .serialize(serializer),
1697 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1698 device: *device,
1699 inode: *inode,
1700 }
1701 .serialize(serializer),
1702 Self::WindowsSpawnFileId {
1703 volume_serial_number,
1704 file_id,
1705 } => RunningImageEvidenceWire::WindowsSpawnFileId {
1706 volume_serial_number: *volume_serial_number,
1707 file_id: *file_id,
1708 }
1709 .serialize(serializer),
1710 Self::Unknown { body, .. } => body.serialize(serializer),
1711 }
1712 }
1713}
1714
1715impl<'de> Deserialize<'de> for RunningImageEvidence {
1716 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1717 where
1718 D: serde::Deserializer<'de>,
1719 {
1720 let (tag, value) = read_tagged(deserializer, "method")?;
1721 match tag.as_str() {
1722 "linux_proc_sha256" => {
1723 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1724 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1725 Ok(Self::LinuxProcSha256 { digest })
1726 }
1727 _ => unreachable!(),
1728 }
1729 }
1730 "macos_spawn_inode" => {
1731 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1732 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1733 Ok(Self::MacosSpawnInode { device, inode })
1734 }
1735 _ => unreachable!(),
1736 }
1737 }
1738 "windows_spawn_file_id" => {
1739 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1740 RunningImageEvidenceWire::WindowsSpawnFileId {
1741 volume_serial_number,
1742 file_id,
1743 } => Ok(Self::WindowsSpawnFileId {
1744 volume_serial_number,
1745 file_id,
1746 }),
1747 _ => unreachable!(),
1748 }
1749 }
1750 _ => Ok(Self::Unknown { tag, body: value }),
1751 }
1752 }
1753}
1754
1755impl Serialize for SupervisorRouteConsumer {
1756 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1757 where
1758 S: Serializer,
1759 {
1760 match self {
1761 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1762 module_id: module_id.clone(),
1763 }
1764 .serialize(serializer),
1765 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1766 connection_id: *connection_id,
1767 }
1768 .serialize(serializer),
1769 Self::Unknown { body, .. } => body.serialize(serializer),
1770 }
1771 }
1772}
1773
1774impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1775 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1776 where
1777 D: serde::Deserializer<'de>,
1778 {
1779 let (tag, value) = read_tagged(deserializer, "kind")?;
1780 match tag.as_str() {
1781 "reserved" => {
1782 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1783 SupervisorRouteConsumerWire::Reserved { module_id } => {
1784 Ok(Self::Reserved { module_id })
1785 }
1786 _ => unreachable!(),
1787 }
1788 }
1789 "direct" => {
1790 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1791 SupervisorRouteConsumerWire::Direct { connection_id } => {
1792 Ok(Self::Direct { connection_id })
1793 }
1794 _ => unreachable!(),
1795 }
1796 }
1797 _ => Ok(Self::Unknown { tag, body: value }),
1798 }
1799 }
1800}
1801
1802impl Serialize for StderrCaptureState {
1803 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1804 where
1805 S: Serializer,
1806 {
1807 match self {
1808 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1809 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1810 reason: reason.clone(),
1811 }
1812 .serialize(serializer),
1813 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1814 reason: reason.clone(),
1815 }
1816 .serialize(serializer),
1817 Self::Unknown { body, .. } => body.serialize(serializer),
1818 }
1819 }
1820}
1821
1822impl<'de> Deserialize<'de> for StderrCaptureState {
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, "state")?;
1828 match tag.as_str() {
1829 "captured" => {
1830 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1831 StderrCaptureStateWire::Captured => Ok(Self::Captured),
1832 _ => unreachable!(),
1833 }
1834 }
1835 "incomplete" => match serde_json::from_value(value.into_value())
1836 .map_err(D::Error::custom)?
1837 {
1838 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1839 _ => unreachable!(),
1840 },
1841 "not_captured" => match serde_json::from_value(value.into_value())
1842 .map_err(D::Error::custom)?
1843 {
1844 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1845 _ => unreachable!(),
1846 },
1847 _ => Ok(Self::Unknown { tag, body: value }),
1848 }
1849 }
1850}
1851
1852impl Serialize for StderrTailEntry {
1853 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1854 where
1855 S: Serializer,
1856 {
1857 match self {
1858 Self::Line {
1859 text,
1860 truncated,
1861 at_ms,
1862 } => StderrTailEntryWire::Line {
1863 text: text.clone(),
1864 truncated: *truncated,
1865 at_ms: *at_ms,
1866 }
1867 .serialize(serializer),
1868 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1869 Self::Unknown { body, .. } => body.serialize(serializer),
1870 }
1871 }
1872}
1873
1874impl<'de> Deserialize<'de> for StderrTailEntry {
1875 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1876 where
1877 D: serde::Deserializer<'de>,
1878 {
1879 let (tag, value) = read_tagged(deserializer, "kind")?;
1880 match tag.as_str() {
1881 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1882 StderrTailEntryWire::Line {
1883 text,
1884 truncated,
1885 at_ms,
1886 } => Ok(Self::Line {
1887 text,
1888 truncated,
1889 at_ms,
1890 }),
1891 _ => unreachable!(),
1892 },
1893 "process_start" => {
1894 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1895 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1896 _ => unreachable!(),
1897 }
1898 }
1899 _ => Ok(Self::Unknown { tag, body: value }),
1900 }
1901 }
1902}
1903
1904fn is_zero_u64(value: &u64) -> bool {
1905 *value == 0
1906}
1907
1908fn default_true() -> bool {
1909 true
1910}
1911
1912#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1914pub struct TerminalHistory {
1915 pub daemon_started_at_ms: u64,
1917 pub entries: Vec<TerminalEntry>,
1918 #[serde(default, skip_serializing_if = "is_zero_u64")]
1921 pub dropped: u64,
1922 #[serde(default, skip_serializing_if = "is_zero_u64")]
1925 pub journal_skipped_lines: u64,
1926 #[serde(default, skip_serializing_if = "is_zero_u64")]
1928 pub journal_read_errors: u64,
1929 #[serde(default, skip_serializing_if = "is_zero_u64")]
1931 pub journal_write_failures: u64,
1932}
1933
1934#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1936pub struct TerminalEntry {
1937 #[serde(default, skip_serializing_if = "Option::is_none")]
1940 pub daemon_incarnation: Option<String>,
1941 #[serde(default, skip_serializing_if = "Option::is_none")]
1942 pub exit_code: Option<i32>,
1943 #[serde(default, skip_serializing_if = "Option::is_none")]
1944 pub exit_signal: Option<i32>,
1945 pub at_ms: u64,
1946 pub disposition: TerminalDisposition,
1947 #[serde(default, skip_serializing_if = "Option::is_none")]
1951 pub exit_kind: Option<TerminalExitKind>,
1952 #[serde(default, skip_serializing_if = "Option::is_none")]
1959 pub disposition_detail: Option<String>,
1960}
1961
1962#[derive(Debug, Clone, PartialEq, Eq)]
1967pub enum TerminalExitKind {
1968 Clean,
1969 Crash,
1970 DeliberateSeverance,
1971 Unknown(String),
1972}
1973
1974impl TerminalExitKind {
1975 fn wire_name(&self) -> &str {
1976 match self {
1977 Self::Clean => "clean",
1978 Self::Crash => "crash",
1979 Self::DeliberateSeverance => "deliberate_severance",
1980 Self::Unknown(value) => value,
1981 }
1982 }
1983}
1984
1985impl Serialize for TerminalExitKind {
1986 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1987 where
1988 S: serde::Serializer,
1989 {
1990 serializer.serialize_str(self.wire_name())
1991 }
1992}
1993
1994impl<'de> Deserialize<'de> for TerminalExitKind {
1995 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1996 where
1997 D: serde::Deserializer<'de>,
1998 {
1999 let value = String::deserialize(deserializer)?;
2000 Ok(match value.as_str() {
2001 "clean" => Self::Clean,
2002 "crash" => Self::Crash,
2003 "deliberate_severance" => Self::DeliberateSeverance,
2004 _ => Self::Unknown(value),
2005 })
2006 }
2007}
2008
2009open_string_enum! {
2010 TerminalDisposition {
2012 Stopped => "stopped",
2013 Disabled => "disabled",
2014 Failed => "failed",
2015 Restarting => "restarting",
2016 DaemonShutdown => "daemon_shutdown",
2021 }
2022}
2023
2024#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2025#[serde(rename_all = "snake_case")]
2026pub enum PollKind {
2027 Status,
2028 Liveness,
2029}
2030
2031#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2043#[non_exhaustive]
2044pub struct CatalogEntry {
2045 pub module_id: String,
2046 #[serde(default, skip_serializing_if = "Option::is_none")]
2048 pub display_name: Option<String>,
2049 #[serde(default = "default_true")]
2060 pub ready: bool,
2061 #[serde(default, skip_serializing_if = "Option::is_none")]
2065 pub not_ready: Option<NotReadyReason>,
2066 #[serde(default, skip_serializing_if = "Option::is_none")]
2087 pub module_version: Option<String>,
2088 #[serde(default, skip_serializing_if = "Option::is_none")]
2091 pub provenance: Option<ManifestProvenance>,
2092 pub roles: Vec<ProviderRole>,
2093 pub control_ops: Vec<String>,
2094 #[serde(default, skip_serializing_if = "Option::is_none")]
2099 pub capabilities: Option<CapabilityDeclarations>,
2100 #[serde(default, skip_serializing_if = "Option::is_none")]
2103 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2104 #[serde(default, skip_serializing_if = "Option::is_none")]
2108 pub events: Option<Vec<EventDeclaration>>,
2109 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2112 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2113 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2116 pub operation_payload: BTreeMap<String, OperationPayload>,
2117 #[serde(default, skip_serializing_if = "Option::is_none")]
2123 pub flow_operations: Option<Vec<String>>,
2124 #[serde(default, skip_serializing_if = "Option::is_none")]
2130 pub confirm_operations: Option<Vec<String>>,
2131 #[serde(default, skip_serializing_if = "Option::is_none")]
2134 pub rich_ui: Option<RichUiDescriptor>,
2135 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2138 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2139 #[serde(default, skip_serializing_if = "is_false")]
2142 pub nonce_verified: bool,
2143}
2144
2145impl CatalogEntry {
2146 #[must_use]
2148 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2149 self.display_name = display_name;
2150 self
2151 }
2152
2153 #[must_use]
2155 pub fn new(
2156 module_id: impl Into<String>,
2157 roles: Vec<ProviderRole>,
2158 control_ops: Vec<String>,
2159 ) -> Self {
2160 Self {
2161 module_id: module_id.into(),
2162 ready: default_true(),
2163 display_name: None,
2164 not_ready: None,
2165 module_version: None,
2166 provenance: None,
2167 roles,
2168 control_ops,
2169 capabilities: None,
2170 self_signals: None,
2171 events: None,
2172 operation_delivery: BTreeMap::new(),
2173 operation_payload: BTreeMap::new(),
2174 flow_operations: None,
2175 confirm_operations: None,
2176 rich_ui: None,
2177 role_declarations: BTreeMap::new(),
2178 nonce_verified: false,
2179 }
2180 }
2181
2182 #[must_use]
2184 pub fn with_operation_payload(
2185 mut self,
2186 operation_payload: BTreeMap<String, OperationPayload>,
2187 ) -> Self {
2188 self.operation_payload = operation_payload;
2189 self
2190 }
2191
2192 #[must_use]
2195 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2196 self.flow_operations = flow_operations;
2197 self
2198 }
2199
2200 #[must_use]
2203 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2204 self.confirm_operations = confirm_operations;
2205 self
2206 }
2207
2208 #[must_use]
2210 pub fn with_ready(mut self, ready: bool) -> Self {
2211 self.ready = ready;
2212 self
2213 }
2214
2215 #[must_use]
2217 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2218 self.not_ready = not_ready;
2219 self
2220 }
2221
2222 #[must_use]
2224 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2225 self.module_version = module_version;
2226 self
2227 }
2228
2229 #[must_use]
2231 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2232 self.provenance = provenance;
2233 self
2234 }
2235
2236 #[must_use]
2238 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2239 self.capabilities = capabilities;
2240 self
2241 }
2242
2243 #[must_use]
2245 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2246 self.self_signals = self_signals;
2247 self
2248 }
2249
2250 #[must_use]
2252 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2253 self.events = events;
2254 self
2255 }
2256
2257 #[must_use]
2260 pub fn with_operation_delivery(
2261 mut self,
2262 operation_delivery: BTreeMap<String, OperationDelivery>,
2263 ) -> Self {
2264 self.operation_delivery = operation_delivery;
2265 self
2266 }
2267
2268 #[must_use]
2270 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2271 self.rich_ui = rich_ui;
2272 self
2273 }
2274
2275 #[must_use]
2277 pub fn with_role_declarations(
2278 mut self,
2279 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2280 ) -> Self {
2281 self.role_declarations = role_declarations;
2282 self
2283 }
2284
2285 #[must_use]
2288 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2289 self.nonce_verified = nonce_verified;
2290 self
2291 }
2292}
2293
2294fn is_false(value: &bool) -> bool {
2295 !value
2296}
2297
2298#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2300pub struct NotReadyReason {
2301 pub reason: String,
2306 #[serde(default, skip_serializing_if = "Option::is_none")]
2309 pub capability: Option<String>,
2310}
2311
2312impl NotReadyReason {
2313 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2314 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2315}
2316
2317#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2318pub struct CapabilityRequirementStatus {
2319 pub consumer: String,
2320 pub capability: String,
2321 pub need: String,
2322 pub verdict: String,
2323 pub episode_seq: u64,
2324 pub config_satisfiable: bool,
2325 pub runtime_available: bool,
2326 pub detail: String,
2327}
2328
2329#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2330pub struct SupervisorRescanResult {
2331 pub added: Vec<String>,
2332 pub removed: Vec<String>,
2333 pub changed_pending_reload: Vec<String>,
2334 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2347 pub enabled_changes: Vec<String>,
2348 pub unchanged: u32,
2349 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2357 pub preview: bool,
2358 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2376 pub restart_required: Vec<String>,
2377 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2381 pub capability_warnings: Vec<String>,
2382 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2389 pub module_actions: Vec<RescanModuleAction>,
2390 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2394 pub earlier_pending: Vec<String>,
2395 #[serde(default, skip_serializing_if = "Option::is_none")]
2398 pub expect: Option<RescanExpect>,
2399}
2400
2401#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2417#[serde(rename_all = "snake_case")]
2418pub enum ModuleProtocol {
2419 #[default]
2423 Subc,
2424 None,
2433}
2434
2435#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2447#[non_exhaustive]
2448pub struct SupervisorEntry {
2449 #[serde(default, skip_serializing_if = "Option::is_none")]
2452 pub waiting_for_previous_pid: Option<u32>,
2453 pub module_id: String,
2454 pub state: String,
2455 #[serde(default, skip_serializing_if = "Option::is_none")]
2459 pub next_retry_at_ms: Option<u64>,
2460 pub enabled: bool,
2461 #[serde(default, skip_serializing_if = "Option::is_none")]
2464 pub configured_enabled: Option<bool>,
2465 pub live: bool,
2475 #[serde(default)]
2479 pub protocol: ModuleProtocol,
2480 #[serde(default, skip_serializing_if = "Option::is_none")]
2483 pub launch_nonce_env: Option<bool>,
2484 #[serde(default, skip_serializing_if = "Option::is_none")]
2490 pub launch_nonce_source: Option<String>,
2491 pub health: SupervisorHealthStatus,
2492 #[serde(default, skip_serializing_if = "Option::is_none")]
2495 pub pending_reload: Option<PendingReloadVerdict>,
2496 #[serde(default)]
2502 pub last_probe_ms: Option<u64>,
2503 #[serde(default, skip_serializing_if = "Option::is_none")]
2507 pub last_exit_code: Option<i32>,
2508 #[serde(default, skip_serializing_if = "Option::is_none")]
2512 pub last_exit_signal: Option<i32>,
2513 #[serde(default, skip_serializing_if = "Option::is_none")]
2517 pub last_exit_ms: Option<u64>,
2518 #[serde(default, skip_serializing_if = "Option::is_none")]
2521 pub last_exit_kind: Option<TerminalExitKind>,
2522 #[serde(default, skip_serializing_if = "Option::is_none")]
2539 pub restart_count: Option<u32>,
2540 #[serde(default, skip_serializing_if = "Option::is_none")]
2543 pub max_restarts: Option<u32>,
2544 #[serde(default, skip_serializing_if = "Option::is_none")]
2547 pub lifetime_restarts: Option<u32>,
2548 #[serde(default, skip_serializing_if = "Option::is_none")]
2552 pub spawn_generation: Option<u64>,
2553 #[serde(default, skip_serializing_if = "Option::is_none")]
2563 pub restart_window_secs: Option<u64>,
2564 #[serde(default, skip_serializing_if = "Option::is_none")]
2568 pub drain_timeout_ms: Option<u64>,
2569 #[serde(default, skip_serializing_if = "Option::is_none")]
2572 pub restart_backoff_ms: Option<u64>,
2573 #[serde(default, skip_serializing_if = "Option::is_none")]
2576 pub restart_max_backoff_ms: Option<u64>,
2577 #[serde(default, skip_serializing_if = "Option::is_none")]
2590 pub resources: Option<ChildResourceUsage>,
2591 #[serde(default, skip_serializing_if = "Option::is_none")]
2593 pub tree: Option<TreeReading>,
2594 #[serde(default, skip_serializing_if = "Option::is_none")]
2598 pub tree_unavailable: Option<String>,
2599 #[serde(default, skip_serializing_if = "Option::is_none")]
2601 pub cpu_last_hour: Option<CpuLastHour>,
2602}
2603
2604impl SupervisorEntry {
2605 #[must_use]
2607 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2608 self.next_retry_at_ms = next_retry_at_ms;
2609 self
2610 }
2611
2612 #[must_use]
2614 pub fn new(
2615 module_id: impl Into<String>,
2616 state: impl Into<String>,
2617 enabled: bool,
2618 live: bool,
2619 health: SupervisorHealthStatus,
2620 ) -> Self {
2621 Self {
2622 module_id: module_id.into(),
2623 state: state.into(),
2624 next_retry_at_ms: None,
2625 waiting_for_previous_pid: None,
2626 enabled,
2627 configured_enabled: None,
2628 live,
2629 protocol: ModuleProtocol::default(),
2630 launch_nonce_env: None,
2631 launch_nonce_source: None,
2632 health,
2633 pending_reload: None,
2634 last_probe_ms: None,
2635 last_exit_code: None,
2636 last_exit_signal: None,
2637 last_exit_ms: None,
2638 last_exit_kind: None,
2639 restart_count: None,
2640 max_restarts: None,
2641 lifetime_restarts: None,
2642 spawn_generation: None,
2643 restart_window_secs: None,
2644 drain_timeout_ms: None,
2645 restart_backoff_ms: None,
2646 restart_max_backoff_ms: None,
2647 resources: None,
2648 tree: None,
2649 tree_unavailable: None,
2650 cpu_last_hour: None,
2651 }
2652 }
2653
2654 #[must_use]
2656 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2657 self.protocol = protocol;
2658 self
2659 }
2660
2661 #[must_use]
2663 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2664 self.configured_enabled = configured_enabled;
2665 self
2666 }
2667
2668 #[must_use]
2670 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2671 self.launch_nonce_env = launch_nonce_env;
2672 self
2673 }
2674
2675 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2676 self.launch_nonce_source = source;
2677 self
2678 }
2679
2680 #[must_use]
2681 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2682 self.waiting_for_previous_pid = pid;
2683 self
2684 }
2685
2686 #[must_use]
2688 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2689 self.pending_reload = pending_reload;
2690 self
2691 }
2692
2693 #[must_use]
2695 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2696 self.last_probe_ms = last_probe_ms;
2697 self
2698 }
2699
2700 #[must_use]
2702 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2703 self.last_exit_code = last_exit_code;
2704 self
2705 }
2706
2707 #[must_use]
2709 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2710 self.last_exit_signal = last_exit_signal;
2711 self
2712 }
2713
2714 #[must_use]
2716 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2717 self.last_exit_ms = last_exit_ms;
2718 self
2719 }
2720
2721 #[must_use]
2723 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2724 self.last_exit_kind = last_exit_kind;
2725 self
2726 }
2727
2728 #[must_use]
2730 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2731 self.restart_count = restart_count;
2732 self
2733 }
2734
2735 #[must_use]
2737 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2738 self.max_restarts = max_restarts;
2739 self
2740 }
2741
2742 #[must_use]
2744 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2745 self.lifetime_restarts = lifetime_restarts;
2746 self
2747 }
2748
2749 #[must_use]
2751 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2752 self.spawn_generation = spawn_generation;
2753 self
2754 }
2755
2756 #[must_use]
2758 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2759 self.restart_window_secs = restart_window_secs;
2760 self
2761 }
2762
2763 #[must_use]
2765 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2766 self.drain_timeout_ms = drain_timeout_ms;
2767 self
2768 }
2769
2770 #[must_use]
2772 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2773 self.restart_backoff_ms = restart_backoff_ms;
2774 self
2775 }
2776
2777 #[must_use]
2779 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2780 self.restart_max_backoff_ms = restart_max_backoff_ms;
2781 self
2782 }
2783
2784 #[must_use]
2786 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2787 self.resources = resources;
2788 self
2789 }
2790
2791 #[must_use]
2793 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
2794 self.tree = tree;
2795 self
2796 }
2797
2798 #[must_use]
2800 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
2801 self.tree_unavailable = reason;
2802 self
2803 }
2804}
2805
2806#[derive(Debug, Clone, PartialEq)]
2809pub enum ChildResourceUsage {
2810 Measured(ChildResourceReading),
2811 Unavailable {
2812 reason: ChildResourceUnavailableReason,
2813 },
2814 Unknown {
2817 tag: String,
2818 body: OrderedJsonObject,
2819 },
2820}
2821
2822#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2825#[non_exhaustive]
2826pub struct ChildResourceReading {
2827 pub memory_bytes: u64,
2830 pub memory_kind: ChildMemoryKind,
2831 #[serde(default, skip_serializing_if = "Option::is_none")]
2834 pub swap_bytes: Option<u64>,
2835 pub cpu_user_ms: u64,
2839 pub cpu_system_ms: u64,
2842}
2843
2844impl ChildResourceReading {
2845 #[must_use]
2847 pub fn new(
2848 memory_bytes: u64,
2849 memory_kind: ChildMemoryKind,
2850 cpu_user_ms: u64,
2851 cpu_system_ms: u64,
2852 ) -> Self {
2853 Self {
2854 memory_bytes,
2855 memory_kind,
2856 cpu_user_ms,
2857 cpu_system_ms,
2858 swap_bytes: None,
2859 }
2860 }
2861
2862 #[must_use]
2864 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
2865 self.swap_bytes = swap_bytes;
2866 self
2867 }
2868}
2869
2870open_string_enum! {
2871 ChildMemoryKind {
2873 PhysFootprint => "phys_footprint",
2877 ResidentSet => "resident_set",
2880 WindowsWorkingSet => "windows_working_set",
2883 }
2884}
2885
2886open_string_enum! {
2887 ChildResourceUnavailableReason {
2889 NotRunning => "not_running",
2891 UnsupportedPlatform => "unsupported_platform",
2893 Unreadable => "unreadable",
2896 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2899 }
2900}
2901
2902#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2903#[serde(rename_all = "snake_case")]
2904pub enum SupervisorHealthStatus {
2905 Ok,
2906 Degraded,
2907 Failing,
2908 Unresponsive,
2909 Unknown,
2910}
2911
2912#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2913pub struct SupervisorHealthEntry {
2914 pub module_id: String,
2915 pub status: SupervisorHealthStatus,
2916 #[serde(default, skip_serializing_if = "Option::is_none")]
2922 pub detail: Option<String>,
2923 #[serde(default, skip_serializing_if = "Option::is_none")]
2928 pub metrics: Option<serde_json::Value>,
2929 pub consecutive_failures: u32,
2930 #[serde(default)]
2933 pub late_answer_count: u64,
2934 #[serde(default, skip_serializing_if = "Option::is_none")]
2936 pub last_late_answer_latency_ms: Option<u64>,
2937 #[serde(default)]
2942 pub last_action: Option<String>,
2943 #[serde(default)]
2946 pub last_action_ms: Option<u64>,
2947 #[serde(default, skip_serializing_if = "Option::is_none")]
2960 pub last_probe_ms: Option<u64>,
2961}
2962
2963#[cfg(test)]
2964mod tests {
2965 #[test]
2966 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2967 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2968 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2969 assert_eq!(decoded.configured_enabled, None);
2970 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2971 }
2972
2973 #[test]
2974 fn configured_enabled_values_round_trip_in_list() {
2975 for enabled in [false, true] {
2976 let entry = SupervisorEntry::new(
2977 "provider",
2978 "running",
2979 true,
2980 true,
2981 SupervisorHealthStatus::Unknown,
2982 )
2983 .with_configured_enabled(Some(enabled));
2984 let entry_json = serde_json::to_value(&entry).unwrap();
2985 assert_eq!(entry_json["configured_enabled"], enabled);
2986 assert_eq!(
2987 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
2988 entry
2989 );
2990 }
2991 }
2992
2993 #[test]
2994 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2995 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2996 volume_serial_number: u64::MAX,
2997 file_id: [
2998 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2999 ],
3000 };
3001 let agreement = super::RunningImageAgreement::Match { evidence };
3002 let encoded = serde_json::to_string(&agreement).unwrap();
3003 assert!(encoded.contains("windows_spawn_file_id"));
3004 assert_eq!(
3005 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3006 agreement
3007 );
3008 }
3009
3010 #[test]
3011 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3012 assert_eq!(
3013 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3014 device: 7,
3015 inode: 11
3016 })
3017 .unwrap(),
3018 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3019 );
3020 assert_eq!(
3021 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3022 digest: "abc".to_owned()
3023 })
3024 .unwrap(),
3025 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3026 );
3027 }
3028 use super::*;
3029 use subc_protocol::{BindIdentity, RouteTarget};
3030
3031 #[test]
3032 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3033 let entry = TerminalEntry {
3034 daemon_incarnation: Some("daemon-before-restart".into()),
3035 exit_code: Some(1),
3036 exit_signal: None,
3037 at_ms: 1_700_000_000_123,
3038 disposition: TerminalDisposition::Restarting,
3039 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3040 disposition_detail: None,
3041 };
3042 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3043 assert_eq!(
3044 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3045 ["exit_kind"],
3046 "deliberate_severance"
3047 );
3048
3049 #[derive(serde::Deserialize)]
3050 struct LegacyTerminalEntry {
3051 exit_code: Option<i32>,
3052 exit_signal: Option<i32>,
3053 at_ms: u64,
3054 disposition: TerminalDisposition,
3055 }
3056
3057 let decoded: LegacyTerminalEntry =
3058 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3059 assert_eq!(decoded.exit_code, Some(1));
3060 assert_eq!(decoded.exit_signal, None);
3061 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3062 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3063
3064 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3065 let future: TerminalEntry =
3066 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3067 assert_eq!(
3068 future.exit_kind,
3069 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3070 );
3071 }
3072
3073 #[test]
3074 fn terminal_incarnation_is_optional_for_older_daemons() {
3075 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3076 "at_ms": 123,
3077 "disposition": "stopped"
3078 }))
3079 .unwrap();
3080 let encoded = serde_json::to_value(&entry).unwrap();
3081 assert_eq!(
3082 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3083 (None, None)
3084 );
3085 }
3086
3087 #[test]
3088 fn route_poll_uses_kind_field() {
3089 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3090 route_channel: 7,
3091 route_epoch: 11,
3092 kind: PollKind::Status,
3093 })
3094 .unwrap();
3095
3096 assert_eq!(body["op"], "route.poll");
3097 assert_eq!(body["route_epoch"], 11);
3098 assert_eq!(body["kind"], "status");
3099 assert!(body.get("op").is_some());
3100 }
3101
3102 #[test]
3103 fn route_open_is_internally_tagged() {
3104 let request = ClientControlRequest::RouteOpen {
3105 busy_refusals: None,
3106 target: RouteTarget::ToolProvider {
3107 module_id: "aft".to_string(),
3108 },
3109 identity: BindIdentity::new("opencode", "session-1"),
3110 consumer_identity: None,
3111 consumer_capabilities: None,
3112 role_versions: None,
3113 admission_facts: None,
3114 scope: None,
3115 };
3116
3117 let body = serde_json::to_value(request).unwrap();
3118 assert_eq!(body["op"], "route.open");
3119 assert_eq!(body["target"]["kind"], "tool_provider");
3120 assert!(body.get("consumer_identity").is_none());
3121 assert!(body.get("consumer_capabilities").is_none());
3122 assert!(body.get("role_versions").is_none());
3123 }
3124
3125 #[test]
3126 fn route_open_without_optional_fields_still_decodes() {
3127 let body = serde_json::json!({
3128 "op": "route.open",
3129 "target": { "kind": "tool_provider", "module_id": "aft" },
3130 "identity": {
3131 "project_root": "/tmp/project",
3132 "harness": "opencode",
3133 "session": "session-1"
3134 }
3135 });
3136
3137 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3138 let ClientControlRequest::RouteOpen {
3139 consumer_identity,
3140 consumer_capabilities,
3141 role_versions,
3142 admission_facts,
3143 ..
3144 } = decoded
3145 else {
3146 panic!("decoded wrong request variant");
3147 };
3148 assert_eq!(consumer_identity, None);
3149 assert_eq!(consumer_capabilities, None);
3150 assert_eq!(role_versions, None);
3151 assert_eq!(admission_facts, None);
3152 }
3153
3154 #[test]
3155 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3156 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3157 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3158 match decoded {
3159 ClientControlPush::RouteClosed {
3160 excluded_subscriptions,
3161 terminal,
3162 ..
3163 } => {
3164 assert_eq!(excluded_subscriptions, 0);
3165 assert_eq!(terminal, None);
3166 }
3167 other => panic!("unexpected push: {other:?}"),
3168 }
3169 assert!(!serde_json::to_string(&decoded)
3170 .unwrap()
3171 .contains("terminal"));
3172 }
3173
3174 #[test]
3175 fn old_route_closed_decoder_ignores_new_terminal_field() {
3176 #[derive(serde::Deserialize)]
3177 #[serde(tag = "op")]
3178 enum LegacyClientControlPush {
3179 #[serde(rename = "route.closed")]
3180 RouteClosed {
3181 module_id: String,
3182 reason: RouteCloseReason,
3183 drained: bool,
3184 abandoned: u32,
3185 },
3186 }
3187
3188 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3189 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3190 match decoded {
3191 LegacyClientControlPush::RouteClosed {
3192 module_id,
3193 reason,
3194 drained,
3195 abandoned,
3196 } => {
3197 assert_eq!(module_id, "aft-tools");
3198 assert_eq!(reason, RouteCloseReason::Crash);
3199 assert!(!drained);
3200 assert_eq!(abandoned, 0);
3201 }
3202 }
3203 }
3204
3205 #[test]
3206 fn supervisor_routes_is_a_control_plane_request() {
3207 let body = serde_json::json!({
3208 "op": "supervisor.routes",
3209 "module_id": "aft"
3210 });
3211
3212 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3213 assert_eq!(serde_json::to_value(request).unwrap(), body);
3214 }
3215
3216 #[test]
3217 fn diagnostic_string_enums_retain_unknown_wire_values() {
3218 let reason: RunningImageUnavailableReason =
3219 serde_json::from_str("\"future_reason\"").unwrap();
3220 let disposition: TerminalDisposition =
3221 serde_json::from_str("\"future_disposition\"").unwrap();
3222
3223 assert_eq!(
3224 reason,
3225 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3226 );
3227 assert_eq!(
3228 disposition,
3229 TerminalDisposition::Unknown("future_disposition".to_string())
3230 );
3231 }
3232
3233 #[test]
3234 fn diagnostic_string_enums_preserve_existing_wire_names() {
3235 let names = [
3236 (RunningImageUnavailableReason::NotRunning, "not_running"),
3237 (
3238 RunningImageUnavailableReason::UnsupportedPlatform,
3239 "unsupported_platform",
3240 ),
3241 (
3242 RunningImageUnavailableReason::RunningExecutableUnreadable,
3243 "running_executable_unreadable",
3244 ),
3245 (
3246 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3247 "running_executable_permission_denied",
3248 ),
3249 (
3250 RunningImageUnavailableReason::ProcessHidden,
3251 "process_hidden",
3252 ),
3253 (
3254 RunningImageUnavailableReason::SpawnedPathUnreadable,
3255 "spawned_path_unreadable",
3256 ),
3257 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3258 (
3259 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3260 "process_identity_unconfirmed",
3261 ),
3262 ];
3263 for (value, expected) in names {
3264 let wire = serde_json::to_string(&value).unwrap();
3265 assert_eq!(wire, format!("\"{expected}\""));
3266 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3267 assert_eq!(decoded, value);
3268 }
3269
3270 for (value, expected) in [
3271 (TerminalDisposition::Stopped, "stopped"),
3272 (TerminalDisposition::Disabled, "disabled"),
3273 (TerminalDisposition::Failed, "failed"),
3274 (TerminalDisposition::Restarting, "restarting"),
3275 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3276 ] {
3277 let wire = serde_json::to_string(&value).unwrap();
3278 assert_eq!(wire, format!("\"{expected}\""));
3279 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3280 assert_eq!(decoded, value);
3281 }
3282 }
3283
3284 #[test]
3285 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3286 let entry = SupervisorEntry::new(
3287 "waiting-module",
3288 "starting",
3289 true,
3290 false,
3291 SupervisorHealthStatus::Unknown,
3292 );
3293 let old_wire = serde_json::to_value(&entry).unwrap();
3294 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3295 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3296 assert_eq!(decoded.waiting_for_previous_pid, None);
3297 let entry = entry.with_waiting_for_previous_pid(Some(42));
3298 let wire = serde_json::to_value(&entry).unwrap();
3299 assert_eq!(wire["waiting_for_previous_pid"], 42);
3300 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3301 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3302 }
3303
3304 #[test]
3305 fn diagnostic_string_enums_reject_non_string_bodies() {
3306 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3307 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3308 }
3309
3310 #[test]
3311 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3312 let body = serde_json::json!({
3313 "op": "supervisor.provenance",
3314 "daemon": {
3315 "daemon_build": {},
3316 "daemon_observed": {
3317 "running_image": {
3318 "status": "unavailable",
3319 "reason": "not_running"
3320 }
3321 }
3322 },
3323 "modules": [
3324 {
3325 "module_id": "future",
3326 "module_declared": { "status": "unverifiable" },
3327 "daemon_observed": {
3328 "running_image": {
3329 "status": "unavailable",
3330 "reason": "future_reason"
3331 }
3332 }
3333 },
3334 {
3335 "module_id": "healthy-a",
3336 "module_declared": { "status": "unverifiable" },
3337 "daemon_observed": {
3338 "running_image": {
3339 "status": "match",
3340 "evidence": {
3341 "method": "linux_proc_sha256",
3342 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3343 }
3344 }
3345 }
3346 },
3347 {
3348 "module_id": "healthy-b",
3349 "module_declared": { "status": "unverifiable" },
3350 "daemon_observed": {
3351 "running_image": {
3352 "status": "unavailable",
3353 "reason": "unsupported_platform"
3354 }
3355 }
3356 }
3357 ]
3358 });
3359
3360 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3361 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3362 panic!("decoded wrong response variant");
3363 };
3364 assert_eq!(modules.len(), 3);
3365 assert_eq!(modules[0].module_id, "future");
3366 assert_eq!(
3367 modules[0].daemon_observed.running_image,
3368 RunningImageAgreement::Unavailable {
3369 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3370 }
3371 );
3372 assert_eq!(modules[1].module_id, "healthy-a");
3373 assert_eq!(modules[2].module_id, "healthy-b");
3374 }
3375
3376 #[test]
3377 fn tagged_unknown_values_retain_tag_and_body() {
3378 macro_rules! assert_unknown_round_trip {
3379 ($ty:ident, $field:literal, $value:expr) => {
3380 let value = $value;
3381 let wire = serde_json::to_string(&value).unwrap();
3382 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3383 match decoded {
3384 $ty::Unknown { tag, body } => {
3385 assert_eq!(tag, value[$field].as_str().unwrap());
3386 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3387 }
3388 _ => panic!("decoded known variant"),
3389 }
3390 };
3391 }
3392
3393 assert_unknown_round_trip!(
3394 ModuleDeclaredProvenance,
3395 "status",
3396 serde_json::json!({"status": "future", "build": {"version": 7}})
3397 );
3398 assert_unknown_round_trip!(
3399 RunningImageAgreement,
3400 "status",
3401 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3402 );
3403 assert_unknown_round_trip!(
3404 RunningImageEvidence,
3405 "method",
3406 serde_json::json!({"method": "future", "digest": "abc"})
3407 );
3408 assert_unknown_round_trip!(
3409 SupervisorRouteConsumer,
3410 "kind",
3411 serde_json::json!({"kind": "future", "module_id": "m"})
3412 );
3413 assert_unknown_round_trip!(
3414 StderrCaptureState,
3415 "state",
3416 serde_json::json!({"state": "future", "reason": "because"})
3417 );
3418 assert_unknown_round_trip!(
3419 StderrTailEntry,
3420 "kind",
3421 serde_json::json!({"kind": "future", "text": "line"})
3422 );
3423 assert_unknown_round_trip!(
3424 ChildResourceUsage,
3425 "status",
3426 serde_json::json!({"status": "future", "memory_bytes": 1})
3427 );
3428 }
3429
3430 #[test]
3431 fn child_resource_usage_round_trips_both_known_states() {
3432 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3433 memory_bytes: 0,
3434 memory_kind: ChildMemoryKind::ResidentSet,
3435 swap_bytes: Some(0),
3436 cpu_user_ms: 0,
3437 cpu_system_ms: 0,
3438 });
3439 let wire = serde_json::to_value(&measured).unwrap();
3440 assert_eq!(
3441 wire,
3442 serde_json::json!({
3443 "status": "measured",
3444 "memory_bytes": 0,
3445 "memory_kind": "resident_set",
3446 "swap_bytes": 0,
3447 "cpu_user_ms": 0,
3448 "cpu_system_ms": 0
3449 })
3450 );
3451 assert_eq!(
3452 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3453 measured
3454 );
3455
3456 let unavailable = ChildResourceUsage::Unavailable {
3457 reason: ChildResourceUnavailableReason::NotRunning,
3458 };
3459 let wire = serde_json::to_value(&unavailable).unwrap();
3460 assert_eq!(
3461 wire,
3462 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3463 );
3464 assert_eq!(
3465 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3466 unavailable
3467 );
3468 }
3469
3470 #[test]
3471 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3472 let stamped: StderrTailEntry = serde_json::from_str(
3476 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3477 )
3478 .unwrap();
3479 assert_eq!(
3480 stamped,
3481 StderrTailEntry::Line {
3482 text: "boom".to_string(),
3483 truncated: true,
3484 at_ms: Some(1_789_801_440_685),
3485 }
3486 );
3487 let unstamped: StderrTailEntry =
3488 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3489 assert_eq!(
3490 unstamped,
3491 StderrTailEntry::Line {
3492 text: "boom".to_string(),
3493 truncated: false,
3494 at_ms: None,
3495 }
3496 );
3497 assert_eq!(
3500 serde_json::to_string(&unstamped).unwrap(),
3501 r#"{"kind":"line","text":"boom"}"#
3502 );
3503 assert_eq!(
3504 serde_json::to_value(&stamped).unwrap()["at_ms"],
3505 serde_json::json!(1_789_801_440_685u64)
3506 );
3507 }
3508
3509 #[test]
3510 fn tagged_unknown_values_round_trip_the_original_json() {
3511 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3512 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3513 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3514 }
3515
3516 #[test]
3517 fn tagged_unknown_values_round_trip_trailing_tag() {
3518 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3519 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3520 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3521
3522 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3523 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3524 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3525 }
3526
3527 #[test]
3528 fn tagged_unknown_values_round_trip_middle_tag() {
3529 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3530 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3531 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3532
3533 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3534 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3535 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3536 }
3537
3538 #[test]
3539 fn tagged_unknown_values_round_trip_deep_payload() {
3540 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3541 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3542 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3543
3544 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3545 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3546 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3547 }
3548
3549 #[test]
3550 fn tagged_unknown_values_reject_non_object_bodies() {
3551 for wire in ["42", r#""future""#, "[]"] {
3552 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3553 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3554 }
3555 }
3556
3557 #[test]
3558 fn duplicate_discriminators_reject_without_panicking() {
3559 assert_eq!(
3560 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3561 .unwrap(),
3562 ModuleDeclaredProvenance::Unverifiable
3563 );
3564 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3565 .unwrap()
3566 {
3567 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3568 _ => panic!("future discriminator decoded as a known variant"),
3569 }
3570
3571 let wires = [
3572 r#"{"status":"reported","status":"unverifiable"}"#,
3573 r#"{"status":"unverifiable","status":"reported"}"#,
3574 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3575 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3576 ];
3577
3578 for wire in wires {
3579 let result =
3580 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3581 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3582 assert!(
3583 result.unwrap().is_err(),
3584 "duplicate discriminator decoded: {wire}"
3585 );
3586 }
3587
3588 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3589 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3590 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3591 assert!(
3592 result.unwrap().is_err(),
3593 "duplicate discriminator decoded: {wire}"
3594 );
3595 }
3596
3597 #[test]
3598 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3599 let known_wire =
3600 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3601 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3602 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3603
3604 for wire in [
3605 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3606 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3607 ] {
3608 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3609 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3610 }
3611
3612 for wire in [
3613 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3614 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3615 ] {
3616 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3617 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3618 }
3619
3620 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3621 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3622 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3623
3624 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3625 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3626 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3627 }
3628
3629 #[test]
3630 fn tagged_unknown_member_does_not_discard_known_siblings() {
3631 let body = serde_json::json!({
3632 "modules": [{
3633 "module_id": "target",
3634 "routes": [
3635 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3636 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3637 ]
3638 }]
3639 });
3640 let decoded: ClientControlResponse = serde_json::from_value(
3641 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3642 )
3643 .unwrap();
3644 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3645 panic!("decoded wrong response variant");
3646 };
3647 assert_eq!(modules[0].routes.len(), 2);
3648 assert_eq!(
3649 modules[0].routes[1].consumer,
3650 SupervisorRouteConsumer::Direct { connection_id: 7 }
3651 );
3652 }
3653}
3654
3655#[cfg(test)]
3656mod launch_nonce_redaction_tests {
3657 use super::*;
3658
3659 const NONCE: &str = "nonce-f00dfeed1234abcd";
3660
3661 fn identity() -> ConsumerIdentity {
3662 ConsumerIdentity {
3663 module_id: "wernicke".to_string(),
3664 launch_nonce: NONCE.to_string(),
3665 }
3666 }
3667
3668 #[test]
3669 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3670 let printed = format!("{:?}", identity());
3671 assert!(printed.contains("wernicke"), "{printed}");
3672 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3673 }
3674
3675 #[test]
3676 fn route_open_request_debug_never_prints_the_nonce() {
3677 let request = ClientControlRequest::RouteOpen {
3678 busy_refusals: None,
3679 target: subc_protocol::RouteTarget::ToolProvider {
3680 module_id: "broca".to_string(),
3681 },
3682 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
3683 consumer_identity: Some(identity()),
3684 consumer_capabilities: None,
3685 role_versions: None,
3686 admission_facts: None,
3687 scope: None,
3688 };
3689 let printed = format!("{request:?}");
3690 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3691 }
3692}