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")]
2600 pub tree_unavailable: Option<String>,
2601 #[serde(default, skip_serializing_if = "Option::is_none")]
2603 pub cpu_last_hour: Option<CpuLastHour>,
2604}
2605
2606impl SupervisorEntry {
2607 #[must_use]
2609 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2610 self.next_retry_at_ms = next_retry_at_ms;
2611 self
2612 }
2613
2614 #[must_use]
2616 pub fn new(
2617 module_id: impl Into<String>,
2618 state: impl Into<String>,
2619 enabled: bool,
2620 live: bool,
2621 health: SupervisorHealthStatus,
2622 ) -> Self {
2623 Self {
2624 module_id: module_id.into(),
2625 state: state.into(),
2626 next_retry_at_ms: None,
2627 waiting_for_previous_pid: None,
2628 enabled,
2629 configured_enabled: None,
2630 live,
2631 protocol: ModuleProtocol::default(),
2632 launch_nonce_env: None,
2633 launch_nonce_source: None,
2634 health,
2635 pending_reload: None,
2636 last_probe_ms: None,
2637 last_exit_code: None,
2638 last_exit_signal: None,
2639 last_exit_ms: None,
2640 last_exit_kind: None,
2641 restart_count: None,
2642 max_restarts: None,
2643 lifetime_restarts: None,
2644 spawn_generation: None,
2645 restart_window_secs: None,
2646 drain_timeout_ms: None,
2647 restart_backoff_ms: None,
2648 restart_max_backoff_ms: None,
2649 resources: None,
2650 tree: None,
2651 tree_unavailable: None,
2652 cpu_last_hour: None,
2653 }
2654 }
2655
2656 #[must_use]
2658 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2659 self.protocol = protocol;
2660 self
2661 }
2662
2663 #[must_use]
2665 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2666 self.configured_enabled = configured_enabled;
2667 self
2668 }
2669
2670 #[must_use]
2672 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2673 self.launch_nonce_env = launch_nonce_env;
2674 self
2675 }
2676
2677 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2678 self.launch_nonce_source = source;
2679 self
2680 }
2681
2682 #[must_use]
2683 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2684 self.waiting_for_previous_pid = pid;
2685 self
2686 }
2687
2688 #[must_use]
2690 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2691 self.pending_reload = pending_reload;
2692 self
2693 }
2694
2695 #[must_use]
2697 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2698 self.last_probe_ms = last_probe_ms;
2699 self
2700 }
2701
2702 #[must_use]
2704 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2705 self.last_exit_code = last_exit_code;
2706 self
2707 }
2708
2709 #[must_use]
2711 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2712 self.last_exit_signal = last_exit_signal;
2713 self
2714 }
2715
2716 #[must_use]
2718 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2719 self.last_exit_ms = last_exit_ms;
2720 self
2721 }
2722
2723 #[must_use]
2725 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2726 self.last_exit_kind = last_exit_kind;
2727 self
2728 }
2729
2730 #[must_use]
2732 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2733 self.restart_count = restart_count;
2734 self
2735 }
2736
2737 #[must_use]
2739 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2740 self.max_restarts = max_restarts;
2741 self
2742 }
2743
2744 #[must_use]
2746 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2747 self.lifetime_restarts = lifetime_restarts;
2748 self
2749 }
2750
2751 #[must_use]
2753 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2754 self.spawn_generation = spawn_generation;
2755 self
2756 }
2757
2758 #[must_use]
2760 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2761 self.restart_window_secs = restart_window_secs;
2762 self
2763 }
2764
2765 #[must_use]
2767 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2768 self.drain_timeout_ms = drain_timeout_ms;
2769 self
2770 }
2771
2772 #[must_use]
2774 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2775 self.restart_backoff_ms = restart_backoff_ms;
2776 self
2777 }
2778
2779 #[must_use]
2781 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2782 self.restart_max_backoff_ms = restart_max_backoff_ms;
2783 self
2784 }
2785
2786 #[must_use]
2788 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2789 self.resources = resources;
2790 self
2791 }
2792
2793 #[must_use]
2795 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
2796 self.tree = tree;
2797 self
2798 }
2799
2800 #[must_use]
2802 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
2803 self.tree_unavailable = reason;
2804 self
2805 }
2806}
2807
2808#[derive(Debug, Clone, PartialEq)]
2811pub enum ChildResourceUsage {
2812 Measured(ChildResourceReading),
2813 Unavailable {
2814 reason: ChildResourceUnavailableReason,
2815 },
2816 Unknown {
2819 tag: String,
2820 body: OrderedJsonObject,
2821 },
2822}
2823
2824#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2827#[non_exhaustive]
2828pub struct ChildResourceReading {
2829 pub memory_bytes: u64,
2832 pub memory_kind: ChildMemoryKind,
2833 #[serde(default, skip_serializing_if = "Option::is_none")]
2836 pub swap_bytes: Option<u64>,
2837 pub cpu_user_ms: u64,
2841 pub cpu_system_ms: u64,
2844}
2845
2846impl ChildResourceReading {
2847 #[must_use]
2849 pub fn new(
2850 memory_bytes: u64,
2851 memory_kind: ChildMemoryKind,
2852 cpu_user_ms: u64,
2853 cpu_system_ms: u64,
2854 ) -> Self {
2855 Self {
2856 memory_bytes,
2857 memory_kind,
2858 cpu_user_ms,
2859 cpu_system_ms,
2860 swap_bytes: None,
2861 }
2862 }
2863
2864 #[must_use]
2866 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
2867 self.swap_bytes = swap_bytes;
2868 self
2869 }
2870}
2871
2872open_string_enum! {
2873 ChildMemoryKind {
2875 PhysFootprint => "phys_footprint",
2879 ResidentSet => "resident_set",
2882 WindowsWorkingSet => "windows_working_set",
2885 }
2886}
2887
2888open_string_enum! {
2889 ChildResourceUnavailableReason {
2891 NotRunning => "not_running",
2893 UnsupportedPlatform => "unsupported_platform",
2895 Unreadable => "unreadable",
2898 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2901 }
2902}
2903
2904#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2905#[serde(rename_all = "snake_case")]
2906pub enum SupervisorHealthStatus {
2907 Ok,
2908 Degraded,
2909 Failing,
2910 Unresponsive,
2911 Unknown,
2912}
2913
2914#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2915pub struct SupervisorHealthEntry {
2916 pub module_id: String,
2917 pub status: SupervisorHealthStatus,
2918 #[serde(default, skip_serializing_if = "Option::is_none")]
2924 pub detail: Option<String>,
2925 #[serde(default, skip_serializing_if = "Option::is_none")]
2930 pub metrics: Option<serde_json::Value>,
2931 pub consecutive_failures: u32,
2932 #[serde(default)]
2935 pub late_answer_count: u64,
2936 #[serde(default, skip_serializing_if = "Option::is_none")]
2938 pub last_late_answer_latency_ms: Option<u64>,
2939 #[serde(default)]
2944 pub last_action: Option<String>,
2945 #[serde(default)]
2948 pub last_action_ms: Option<u64>,
2949 #[serde(default, skip_serializing_if = "Option::is_none")]
2962 pub last_probe_ms: Option<u64>,
2963}
2964
2965#[cfg(test)]
2966mod tests {
2967 #[test]
2968 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2969 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2970 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2971 assert_eq!(decoded.configured_enabled, None);
2972 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2973 }
2974
2975 #[test]
2976 fn configured_enabled_values_round_trip_in_list() {
2977 for enabled in [false, true] {
2978 let entry = SupervisorEntry::new(
2979 "provider",
2980 "running",
2981 true,
2982 true,
2983 SupervisorHealthStatus::Unknown,
2984 )
2985 .with_configured_enabled(Some(enabled));
2986 let entry_json = serde_json::to_value(&entry).unwrap();
2987 assert_eq!(entry_json["configured_enabled"], enabled);
2988 assert_eq!(
2989 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
2990 entry
2991 );
2992 }
2993 }
2994
2995 #[test]
2996 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2997 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2998 volume_serial_number: u64::MAX,
2999 file_id: [
3000 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3001 ],
3002 };
3003 let agreement = super::RunningImageAgreement::Match { evidence };
3004 let encoded = serde_json::to_string(&agreement).unwrap();
3005 assert!(encoded.contains("windows_spawn_file_id"));
3006 assert_eq!(
3007 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3008 agreement
3009 );
3010 }
3011
3012 #[test]
3013 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3014 assert_eq!(
3015 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3016 device: 7,
3017 inode: 11
3018 })
3019 .unwrap(),
3020 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3021 );
3022 assert_eq!(
3023 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3024 digest: "abc".to_owned()
3025 })
3026 .unwrap(),
3027 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3028 );
3029 }
3030 use super::*;
3031 use subc_protocol::{BindIdentity, RouteTarget};
3032
3033 #[test]
3034 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3035 let entry = TerminalEntry {
3036 daemon_incarnation: Some("daemon-before-restart".into()),
3037 exit_code: Some(1),
3038 exit_signal: None,
3039 at_ms: 1_700_000_000_123,
3040 disposition: TerminalDisposition::Restarting,
3041 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3042 disposition_detail: None,
3043 };
3044 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3045 assert_eq!(
3046 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3047 ["exit_kind"],
3048 "deliberate_severance"
3049 );
3050
3051 #[derive(serde::Deserialize)]
3052 struct LegacyTerminalEntry {
3053 exit_code: Option<i32>,
3054 exit_signal: Option<i32>,
3055 at_ms: u64,
3056 disposition: TerminalDisposition,
3057 }
3058
3059 let decoded: LegacyTerminalEntry =
3060 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3061 assert_eq!(decoded.exit_code, Some(1));
3062 assert_eq!(decoded.exit_signal, None);
3063 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3064 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3065
3066 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3067 let future: TerminalEntry =
3068 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3069 assert_eq!(
3070 future.exit_kind,
3071 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3072 );
3073 }
3074
3075 #[test]
3076 fn terminal_incarnation_is_optional_for_older_daemons() {
3077 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3078 "at_ms": 123,
3079 "disposition": "stopped"
3080 }))
3081 .unwrap();
3082 let encoded = serde_json::to_value(&entry).unwrap();
3083 assert_eq!(
3084 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3085 (None, None)
3086 );
3087 }
3088
3089 #[test]
3090 fn route_poll_uses_kind_field() {
3091 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3092 route_channel: 7,
3093 route_epoch: 11,
3094 kind: PollKind::Status,
3095 })
3096 .unwrap();
3097
3098 assert_eq!(body["op"], "route.poll");
3099 assert_eq!(body["route_epoch"], 11);
3100 assert_eq!(body["kind"], "status");
3101 assert!(body.get("op").is_some());
3102 }
3103
3104 #[test]
3105 fn route_open_is_internally_tagged() {
3106 let request = ClientControlRequest::RouteOpen {
3107 busy_refusals: None,
3108 target: RouteTarget::ToolProvider {
3109 module_id: "aft".to_string(),
3110 },
3111 identity: BindIdentity::new("opencode", "session-1"),
3112 consumer_identity: None,
3113 consumer_capabilities: None,
3114 role_versions: None,
3115 admission_facts: None,
3116 scope: None,
3117 };
3118
3119 let body = serde_json::to_value(request).unwrap();
3120 assert_eq!(body["op"], "route.open");
3121 assert_eq!(body["target"]["kind"], "tool_provider");
3122 assert!(body.get("consumer_identity").is_none());
3123 assert!(body.get("consumer_capabilities").is_none());
3124 assert!(body.get("role_versions").is_none());
3125 }
3126
3127 #[test]
3128 fn route_open_without_optional_fields_still_decodes() {
3129 let body = serde_json::json!({
3130 "op": "route.open",
3131 "target": { "kind": "tool_provider", "module_id": "aft" },
3132 "identity": {
3133 "project_root": "/tmp/project",
3134 "harness": "opencode",
3135 "session": "session-1"
3136 }
3137 });
3138
3139 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3140 let ClientControlRequest::RouteOpen {
3141 consumer_identity,
3142 consumer_capabilities,
3143 role_versions,
3144 admission_facts,
3145 ..
3146 } = decoded
3147 else {
3148 panic!("decoded wrong request variant");
3149 };
3150 assert_eq!(consumer_identity, None);
3151 assert_eq!(consumer_capabilities, None);
3152 assert_eq!(role_versions, None);
3153 assert_eq!(admission_facts, None);
3154 }
3155
3156 #[test]
3157 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3158 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3159 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3160 match decoded {
3161 ClientControlPush::RouteClosed {
3162 excluded_subscriptions,
3163 terminal,
3164 ..
3165 } => {
3166 assert_eq!(excluded_subscriptions, 0);
3167 assert_eq!(terminal, None);
3168 }
3169 other => panic!("unexpected push: {other:?}"),
3170 }
3171 assert!(!serde_json::to_string(&decoded)
3172 .unwrap()
3173 .contains("terminal"));
3174 }
3175
3176 #[test]
3177 fn old_route_closed_decoder_ignores_new_terminal_field() {
3178 #[derive(serde::Deserialize)]
3179 #[serde(tag = "op")]
3180 enum LegacyClientControlPush {
3181 #[serde(rename = "route.closed")]
3182 RouteClosed {
3183 module_id: String,
3184 reason: RouteCloseReason,
3185 drained: bool,
3186 abandoned: u32,
3187 },
3188 }
3189
3190 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3191 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3192 match decoded {
3193 LegacyClientControlPush::RouteClosed {
3194 module_id,
3195 reason,
3196 drained,
3197 abandoned,
3198 } => {
3199 assert_eq!(module_id, "aft-tools");
3200 assert_eq!(reason, RouteCloseReason::Crash);
3201 assert!(!drained);
3202 assert_eq!(abandoned, 0);
3203 }
3204 }
3205 }
3206
3207 #[test]
3208 fn supervisor_routes_is_a_control_plane_request() {
3209 let body = serde_json::json!({
3210 "op": "supervisor.routes",
3211 "module_id": "aft"
3212 });
3213
3214 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3215 assert_eq!(serde_json::to_value(request).unwrap(), body);
3216 }
3217
3218 #[test]
3219 fn diagnostic_string_enums_retain_unknown_wire_values() {
3220 let reason: RunningImageUnavailableReason =
3221 serde_json::from_str("\"future_reason\"").unwrap();
3222 let disposition: TerminalDisposition =
3223 serde_json::from_str("\"future_disposition\"").unwrap();
3224
3225 assert_eq!(
3226 reason,
3227 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3228 );
3229 assert_eq!(
3230 disposition,
3231 TerminalDisposition::Unknown("future_disposition".to_string())
3232 );
3233 }
3234
3235 #[test]
3236 fn diagnostic_string_enums_preserve_existing_wire_names() {
3237 let names = [
3238 (RunningImageUnavailableReason::NotRunning, "not_running"),
3239 (
3240 RunningImageUnavailableReason::UnsupportedPlatform,
3241 "unsupported_platform",
3242 ),
3243 (
3244 RunningImageUnavailableReason::RunningExecutableUnreadable,
3245 "running_executable_unreadable",
3246 ),
3247 (
3248 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3249 "running_executable_permission_denied",
3250 ),
3251 (
3252 RunningImageUnavailableReason::ProcessHidden,
3253 "process_hidden",
3254 ),
3255 (
3256 RunningImageUnavailableReason::SpawnedPathUnreadable,
3257 "spawned_path_unreadable",
3258 ),
3259 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3260 (
3261 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3262 "process_identity_unconfirmed",
3263 ),
3264 ];
3265 for (value, expected) in names {
3266 let wire = serde_json::to_string(&value).unwrap();
3267 assert_eq!(wire, format!("\"{expected}\""));
3268 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3269 assert_eq!(decoded, value);
3270 }
3271
3272 for (value, expected) in [
3273 (TerminalDisposition::Stopped, "stopped"),
3274 (TerminalDisposition::Disabled, "disabled"),
3275 (TerminalDisposition::Failed, "failed"),
3276 (TerminalDisposition::Restarting, "restarting"),
3277 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3278 ] {
3279 let wire = serde_json::to_string(&value).unwrap();
3280 assert_eq!(wire, format!("\"{expected}\""));
3281 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3282 assert_eq!(decoded, value);
3283 }
3284 }
3285
3286 #[test]
3287 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3288 let entry = SupervisorEntry::new(
3289 "waiting-module",
3290 "starting",
3291 true,
3292 false,
3293 SupervisorHealthStatus::Unknown,
3294 );
3295 let old_wire = serde_json::to_value(&entry).unwrap();
3296 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3297 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3298 assert_eq!(decoded.waiting_for_previous_pid, None);
3299 let entry = entry.with_waiting_for_previous_pid(Some(42));
3300 let wire = serde_json::to_value(&entry).unwrap();
3301 assert_eq!(wire["waiting_for_previous_pid"], 42);
3302 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3303 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3304 }
3305
3306 #[test]
3307 fn diagnostic_string_enums_reject_non_string_bodies() {
3308 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3309 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3310 }
3311
3312 #[test]
3313 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3314 let body = serde_json::json!({
3315 "op": "supervisor.provenance",
3316 "daemon": {
3317 "daemon_build": {},
3318 "daemon_observed": {
3319 "running_image": {
3320 "status": "unavailable",
3321 "reason": "not_running"
3322 }
3323 }
3324 },
3325 "modules": [
3326 {
3327 "module_id": "future",
3328 "module_declared": { "status": "unverifiable" },
3329 "daemon_observed": {
3330 "running_image": {
3331 "status": "unavailable",
3332 "reason": "future_reason"
3333 }
3334 }
3335 },
3336 {
3337 "module_id": "healthy-a",
3338 "module_declared": { "status": "unverifiable" },
3339 "daemon_observed": {
3340 "running_image": {
3341 "status": "match",
3342 "evidence": {
3343 "method": "linux_proc_sha256",
3344 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3345 }
3346 }
3347 }
3348 },
3349 {
3350 "module_id": "healthy-b",
3351 "module_declared": { "status": "unverifiable" },
3352 "daemon_observed": {
3353 "running_image": {
3354 "status": "unavailable",
3355 "reason": "unsupported_platform"
3356 }
3357 }
3358 }
3359 ]
3360 });
3361
3362 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3363 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3364 panic!("decoded wrong response variant");
3365 };
3366 assert_eq!(modules.len(), 3);
3367 assert_eq!(modules[0].module_id, "future");
3368 assert_eq!(
3369 modules[0].daemon_observed.running_image,
3370 RunningImageAgreement::Unavailable {
3371 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3372 }
3373 );
3374 assert_eq!(modules[1].module_id, "healthy-a");
3375 assert_eq!(modules[2].module_id, "healthy-b");
3376 }
3377
3378 #[test]
3379 fn tagged_unknown_values_retain_tag_and_body() {
3380 macro_rules! assert_unknown_round_trip {
3381 ($ty:ident, $field:literal, $value:expr) => {
3382 let value = $value;
3383 let wire = serde_json::to_string(&value).unwrap();
3384 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3385 match decoded {
3386 $ty::Unknown { tag, body } => {
3387 assert_eq!(tag, value[$field].as_str().unwrap());
3388 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3389 }
3390 _ => panic!("decoded known variant"),
3391 }
3392 };
3393 }
3394
3395 assert_unknown_round_trip!(
3396 ModuleDeclaredProvenance,
3397 "status",
3398 serde_json::json!({"status": "future", "build": {"version": 7}})
3399 );
3400 assert_unknown_round_trip!(
3401 RunningImageAgreement,
3402 "status",
3403 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3404 );
3405 assert_unknown_round_trip!(
3406 RunningImageEvidence,
3407 "method",
3408 serde_json::json!({"method": "future", "digest": "abc"})
3409 );
3410 assert_unknown_round_trip!(
3411 SupervisorRouteConsumer,
3412 "kind",
3413 serde_json::json!({"kind": "future", "module_id": "m"})
3414 );
3415 assert_unknown_round_trip!(
3416 StderrCaptureState,
3417 "state",
3418 serde_json::json!({"state": "future", "reason": "because"})
3419 );
3420 assert_unknown_round_trip!(
3421 StderrTailEntry,
3422 "kind",
3423 serde_json::json!({"kind": "future", "text": "line"})
3424 );
3425 assert_unknown_round_trip!(
3426 ChildResourceUsage,
3427 "status",
3428 serde_json::json!({"status": "future", "memory_bytes": 1})
3429 );
3430 }
3431
3432 #[test]
3433 fn child_resource_usage_round_trips_both_known_states() {
3434 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3435 memory_bytes: 0,
3436 memory_kind: ChildMemoryKind::ResidentSet,
3437 swap_bytes: Some(0),
3438 cpu_user_ms: 0,
3439 cpu_system_ms: 0,
3440 });
3441 let wire = serde_json::to_value(&measured).unwrap();
3442 assert_eq!(
3443 wire,
3444 serde_json::json!({
3445 "status": "measured",
3446 "memory_bytes": 0,
3447 "memory_kind": "resident_set",
3448 "swap_bytes": 0,
3449 "cpu_user_ms": 0,
3450 "cpu_system_ms": 0
3451 })
3452 );
3453 assert_eq!(
3454 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3455 measured
3456 );
3457
3458 let unavailable = ChildResourceUsage::Unavailable {
3459 reason: ChildResourceUnavailableReason::NotRunning,
3460 };
3461 let wire = serde_json::to_value(&unavailable).unwrap();
3462 assert_eq!(
3463 wire,
3464 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3465 );
3466 assert_eq!(
3467 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3468 unavailable
3469 );
3470 }
3471
3472 #[test]
3473 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3474 let stamped: StderrTailEntry = serde_json::from_str(
3478 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3479 )
3480 .unwrap();
3481 assert_eq!(
3482 stamped,
3483 StderrTailEntry::Line {
3484 text: "boom".to_string(),
3485 truncated: true,
3486 at_ms: Some(1_789_801_440_685),
3487 }
3488 );
3489 let unstamped: StderrTailEntry =
3490 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3491 assert_eq!(
3492 unstamped,
3493 StderrTailEntry::Line {
3494 text: "boom".to_string(),
3495 truncated: false,
3496 at_ms: None,
3497 }
3498 );
3499 assert_eq!(
3502 serde_json::to_string(&unstamped).unwrap(),
3503 r#"{"kind":"line","text":"boom"}"#
3504 );
3505 assert_eq!(
3506 serde_json::to_value(&stamped).unwrap()["at_ms"],
3507 serde_json::json!(1_789_801_440_685u64)
3508 );
3509 }
3510
3511 #[test]
3512 fn tagged_unknown_values_round_trip_the_original_json() {
3513 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3514 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3515 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3516 }
3517
3518 #[test]
3519 fn tagged_unknown_values_round_trip_trailing_tag() {
3520 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3521 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3522 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3523
3524 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3525 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3526 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3527 }
3528
3529 #[test]
3530 fn tagged_unknown_values_round_trip_middle_tag() {
3531 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3532 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3533 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3534
3535 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3536 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3537 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3538 }
3539
3540 #[test]
3541 fn tagged_unknown_values_round_trip_deep_payload() {
3542 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3543 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3544 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3545
3546 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3547 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3548 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3549 }
3550
3551 #[test]
3552 fn tagged_unknown_values_reject_non_object_bodies() {
3553 for wire in ["42", r#""future""#, "[]"] {
3554 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3555 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3556 }
3557 }
3558
3559 #[test]
3560 fn duplicate_discriminators_reject_without_panicking() {
3561 assert_eq!(
3562 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3563 .unwrap(),
3564 ModuleDeclaredProvenance::Unverifiable
3565 );
3566 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3567 .unwrap()
3568 {
3569 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3570 _ => panic!("future discriminator decoded as a known variant"),
3571 }
3572
3573 let wires = [
3574 r#"{"status":"reported","status":"unverifiable"}"#,
3575 r#"{"status":"unverifiable","status":"reported"}"#,
3576 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3577 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3578 ];
3579
3580 for wire in wires {
3581 let result =
3582 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3583 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3584 assert!(
3585 result.unwrap().is_err(),
3586 "duplicate discriminator decoded: {wire}"
3587 );
3588 }
3589
3590 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3591 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3592 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3593 assert!(
3594 result.unwrap().is_err(),
3595 "duplicate discriminator decoded: {wire}"
3596 );
3597 }
3598
3599 #[test]
3600 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3601 let known_wire =
3602 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3603 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3604 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3605
3606 for wire in [
3607 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3608 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3609 ] {
3610 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3611 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3612 }
3613
3614 for wire in [
3615 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3616 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3617 ] {
3618 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3619 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3620 }
3621
3622 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3623 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3624 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3625
3626 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3627 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3628 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3629 }
3630
3631 #[test]
3632 fn tagged_unknown_member_does_not_discard_known_siblings() {
3633 let body = serde_json::json!({
3634 "modules": [{
3635 "module_id": "target",
3636 "routes": [
3637 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3638 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3639 ]
3640 }]
3641 });
3642 let decoded: ClientControlResponse = serde_json::from_value(
3643 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3644 )
3645 .unwrap();
3646 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3647 panic!("decoded wrong response variant");
3648 };
3649 assert_eq!(modules[0].routes.len(), 2);
3650 assert_eq!(
3651 modules[0].routes[1].consumer,
3652 SupervisorRouteConsumer::Direct { connection_id: 7 }
3653 );
3654 }
3655}
3656
3657#[cfg(test)]
3658mod launch_nonce_redaction_tests {
3659 use super::*;
3660
3661 const NONCE: &str = "nonce-f00dfeed1234abcd";
3662
3663 fn identity() -> ConsumerIdentity {
3664 ConsumerIdentity {
3665 module_id: "wernicke".to_string(),
3666 launch_nonce: NONCE.to_string(),
3667 }
3668 }
3669
3670 #[test]
3671 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3672 let printed = format!("{:?}", identity());
3673 assert!(printed.contains("wernicke"), "{printed}");
3674 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3675 }
3676
3677 #[test]
3678 fn route_open_request_debug_never_prints_the_nonce() {
3679 let request = ClientControlRequest::RouteOpen {
3680 busy_refusals: None,
3681 target: subc_protocol::RouteTarget::ToolProvider {
3682 module_id: "broca".to_string(),
3683 },
3684 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
3685 consumer_identity: Some(identity()),
3686 consumer_capabilities: None,
3687 role_versions: None,
3688 admission_facts: None,
3689 scope: None,
3690 };
3691 let printed = format!("{request:?}");
3692 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3693 }
3694}