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)]
748pub struct PendingReloadVerdict {
749 pub path: ReloadPathAgreement,
750 pub image: RunningImageAgreement,
751 #[serde(default, skip_serializing_if = "Option::is_none")]
752 pub spec: Option<LaunchSpecAgreement>,
753}
754
755#[cfg(test)]
756mod launch_spec_wire_tests {
757 use super::*;
758
759 #[test]
760 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
761 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
762 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
763 assert_eq!(parsed.spec, None);
764 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
765 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
766 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
767 assert!(
768 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
769 );
770 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
771 let unavailable = LaunchSpecAgreement::Unavailable {
772 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
773 };
774 let encoded = serde_json::to_string(&unavailable).unwrap();
775 assert_eq!(
776 encoded,
777 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
778 );
779 assert_eq!(
780 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
781 unavailable
782 );
783 }
784}
785
786#[derive(Debug, Clone, PartialEq)]
789pub enum LaunchSpecAgreement {
790 Match,
791 Mismatch,
792 Unavailable {
793 reason: LaunchSpecUnavailableReason,
794 },
795 Unknown {
796 tag: String,
797 body: OrderedJsonObject,
798 },
799}
800
801open_string_enum! {
802 LaunchSpecUnavailableReason {
803 NotRunning => "not_running",
804 SpawnedSpecUnavailable => "spawned_spec_unavailable",
805 }
806}
807
808#[derive(Debug, Clone, PartialEq)]
810pub enum ReloadPathAgreement {
811 Match,
812 Mismatch {
813 configured: PathBuf,
814 spawned_from: PathBuf,
815 },
816 Unavailable {
817 reason: ReloadPathUnavailableReason,
818 },
819 Unknown {
820 tag: String,
821 body: OrderedJsonObject,
822 },
823}
824
825open_string_enum! {
826 ReloadPathUnavailableReason {
828 NotRunning => "not_running",
829 SpawnedPathUnavailable => "spawned_path_unavailable",
830 }
831}
832
833#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
835pub struct SupervisorDaemonProvenance {
836 pub daemon_build: DaemonBuildProvenance,
837 pub daemon_observed: DaemonObservedProcess,
838}
839
840#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
842pub struct DaemonBuildProvenance {
843 #[serde(default, skip_serializing_if = "Option::is_none")]
844 pub build_git_sha: Option<String>,
845 #[serde(default, skip_serializing_if = "Option::is_none")]
846 pub build_lock_digest: Option<String>,
847}
848
849#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
851pub struct DaemonObservedProcess {
852 #[serde(default, skip_serializing_if = "Option::is_none")]
853 pub pid: Option<u32>,
854 #[serde(default, skip_serializing_if = "Option::is_none")]
859 pub started_at_ms: Option<u64>,
860 pub running_image: RunningImageAgreement,
861}
862
863#[derive(Debug, Clone, PartialEq)]
865pub enum RunningImageAgreement {
866 Match {
867 evidence: RunningImageEvidence,
868 },
869 Mismatch {
870 running: RunningImageEvidence,
871 disk: RunningImageEvidence,
872 },
873 Unavailable {
874 reason: RunningImageUnavailableReason,
875 },
876 Unknown {
879 tag: String,
880 body: OrderedJsonObject,
881 },
882}
883
884#[derive(Debug, Clone, PartialEq)]
886pub enum RunningImageEvidence {
887 LinuxProcSha256 {
888 digest: String,
889 },
890 MacosSpawnInode {
891 device: u64,
892 inode: u64,
893 },
894 WindowsSpawnFileId {
896 volume_serial_number: u64,
897 file_id: [u8; 16],
898 },
899 Unknown {
902 tag: String,
903 body: OrderedJsonObject,
904 },
905}
906
907open_string_enum! {
908 RunningImageUnavailableReason {
910 NotRunning => "not_running",
911 NotYetMeasured => "not_yet_measured",
912 UnsupportedPlatform => "unsupported_platform",
913 RunningExecutableUnreadable => "running_executable_unreadable",
914 RunningExecutablePermissionDenied => "running_executable_permission_denied",
915 ProcessHidden => "process_hidden",
916 SpawnedPathUnreadable => "spawned_path_unreadable",
917 HashFailed => "hash_failed",
918 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
919 }
920}
921
922#[derive(Debug, Clone, PartialEq)]
928pub enum SupervisorRouteConsumer {
929 Reserved {
930 module_id: String,
931 },
932 Direct {
933 connection_id: u64,
934 },
935 Unknown {
938 tag: String,
939 body: OrderedJsonObject,
940 },
941}
942
943#[derive(Debug, Clone, PartialEq)]
950pub enum StderrCaptureState {
951 Captured,
954 Incomplete { reason: String },
956 NotCaptured { reason: String },
958 Unknown {
961 tag: String,
962 body: OrderedJsonObject,
963 },
964}
965
966#[derive(Debug, Clone, PartialEq)]
967pub enum StderrTailEntry {
968 Line {
969 text: String,
970 truncated: bool,
975 at_ms: Option<u64>,
979 },
980 ProcessStart,
985 Unknown {
988 tag: String,
989 body: OrderedJsonObject,
990 },
991}
992
993#[derive(Debug, Serialize, Deserialize)]
994#[serde(tag = "status", rename_all = "snake_case")]
995enum ModuleDeclaredProvenanceWire {
996 Reported { build: ManifestProvenance },
997 Unverifiable,
998}
999
1000#[derive(Debug, Serialize, Deserialize)]
1001#[serde(tag = "status", rename_all = "snake_case")]
1002enum RunningImageAgreementWire {
1003 Match {
1004 evidence: RunningImageEvidence,
1005 },
1006 Mismatch {
1007 running: RunningImageEvidence,
1008 disk: RunningImageEvidence,
1009 },
1010 Unavailable {
1011 reason: RunningImageUnavailableReason,
1012 },
1013}
1014
1015#[derive(Debug, Serialize, Deserialize)]
1016#[serde(tag = "status", rename_all = "snake_case")]
1017enum ReloadPathAgreementWire {
1018 Match,
1019 Mismatch {
1020 configured: PathBuf,
1021 spawned_from: PathBuf,
1022 },
1023 Unavailable {
1024 reason: ReloadPathUnavailableReason,
1025 },
1026}
1027
1028#[derive(Debug, Serialize, Deserialize)]
1029#[serde(tag = "status", rename_all = "snake_case")]
1030enum LaunchSpecAgreementWire {
1031 Match,
1032 Mismatch,
1033 Unavailable { reason: LaunchSpecUnavailableReason },
1034}
1035
1036#[derive(Debug, Serialize, Deserialize)]
1037#[serde(tag = "method", rename_all = "snake_case")]
1038enum RunningImageEvidenceWire {
1039 LinuxProcSha256 {
1040 digest: String,
1041 },
1042 MacosSpawnInode {
1043 device: u64,
1044 inode: u64,
1045 },
1046 WindowsSpawnFileId {
1047 volume_serial_number: u64,
1048 file_id: [u8; 16],
1049 },
1050}
1051
1052#[derive(Debug, Serialize, Deserialize)]
1053#[serde(tag = "kind", rename_all = "snake_case")]
1054enum SupervisorRouteConsumerWire {
1055 Reserved { module_id: String },
1056 Direct { connection_id: u64 },
1057}
1058
1059#[derive(Debug, Serialize, Deserialize)]
1060#[serde(tag = "state", rename_all = "snake_case")]
1061enum StderrCaptureStateWire {
1062 Captured,
1063 Incomplete { reason: String },
1064 NotCaptured { reason: String },
1065}
1066
1067#[derive(Debug, Serialize, Deserialize)]
1068#[serde(tag = "status", rename_all = "snake_case")]
1069enum ChildResourceUsageWire {
1070 Measured(ChildResourceReading),
1071 Unavailable {
1072 reason: ChildResourceUnavailableReason,
1073 },
1074}
1075
1076#[derive(Debug, Serialize, Deserialize)]
1077#[serde(tag = "kind", rename_all = "snake_case")]
1078enum StderrTailEntryWire {
1079 Line {
1080 text: String,
1081 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1082 truncated: bool,
1083 #[serde(default, skip_serializing_if = "Option::is_none")]
1086 at_ms: Option<u64>,
1087 },
1088 ProcessStart,
1089}
1090
1091#[derive(Debug, Clone, PartialEq)]
1093pub enum OrderedJsonValue {
1094 Null,
1095 Bool(bool),
1096 Number(serde_json::Number),
1097 String(String),
1098 Array(Vec<Self>),
1099 Object(OrderedJsonObject),
1100}
1101
1102#[derive(Debug, Clone, PartialEq)]
1104pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1105
1106impl OrderedJsonObject {
1107 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1109 &self.0
1110 }
1111
1112 fn into_value(self) -> serde_json::Value {
1113 serde_json::Value::Object(
1114 self.0
1115 .into_iter()
1116 .map(|(key, value)| (key, value.into_value()))
1117 .collect(),
1118 )
1119 }
1120}
1121
1122impl OrderedJsonValue {
1123 fn into_value(self) -> serde_json::Value {
1124 match self {
1125 Self::Null => serde_json::Value::Null,
1126 Self::Bool(value) => serde_json::Value::Bool(value),
1127 Self::Number(value) => serde_json::Value::Number(value),
1128 Self::String(value) => serde_json::Value::String(value),
1129 Self::Array(values) => {
1130 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1131 }
1132 Self::Object(value) => value.into_value(),
1133 }
1134 }
1135}
1136
1137impl Serialize for OrderedJsonValue {
1138 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1139 where
1140 S: Serializer,
1141 {
1142 match self {
1143 Self::Null => serializer.serialize_unit(),
1144 Self::Bool(value) => serializer.serialize_bool(*value),
1145 Self::Number(value) => value.serialize(serializer),
1146 Self::String(value) => serializer.serialize_str(value),
1147 Self::Array(values) => values.serialize(serializer),
1148 Self::Object(value) => value.serialize(serializer),
1149 }
1150 }
1151}
1152
1153impl<'de> Deserialize<'de> for OrderedJsonValue {
1154 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1155 where
1156 D: Deserializer<'de>,
1157 {
1158 struct OrderedValueVisitor;
1159
1160 impl<'de> Visitor<'de> for OrderedValueVisitor {
1161 type Value = OrderedJsonValue;
1162
1163 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1164 formatter.write_str("a JSON value with ordered object members")
1165 }
1166
1167 fn visit_unit<E>(self) -> Result<Self::Value, E>
1168 where
1169 E: serde::de::Error,
1170 {
1171 Ok(OrderedJsonValue::Null)
1172 }
1173
1174 fn visit_none<E>(self) -> Result<Self::Value, E>
1175 where
1176 E: serde::de::Error,
1177 {
1178 Ok(OrderedJsonValue::Null)
1179 }
1180
1181 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1182 where
1183 D: Deserializer<'de>,
1184 {
1185 OrderedJsonValue::deserialize(deserializer)
1186 }
1187
1188 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1189 where
1190 E: serde::de::Error,
1191 {
1192 Ok(OrderedJsonValue::Bool(value))
1193 }
1194
1195 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1196 where
1197 E: serde::de::Error,
1198 {
1199 Ok(OrderedJsonValue::Number(value.into()))
1200 }
1201
1202 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1203 where
1204 E: serde::de::Error,
1205 {
1206 Ok(OrderedJsonValue::Number(value.into()))
1207 }
1208
1209 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1210 where
1211 E: serde::de::Error,
1212 {
1213 serde_json::Number::from_f64(value)
1214 .map(OrderedJsonValue::Number)
1215 .ok_or_else(|| E::custom("non-finite JSON number"))
1216 }
1217
1218 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1219 where
1220 E: serde::de::Error,
1221 {
1222 Ok(OrderedJsonValue::String(value.to_owned()))
1223 }
1224
1225 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1226 where
1227 E: serde::de::Error,
1228 {
1229 Ok(OrderedJsonValue::String(value))
1230 }
1231
1232 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1233 where
1234 A: SeqAccess<'de>,
1235 {
1236 let mut values = Vec::new();
1237 while let Some(value) = sequence.next_element()? {
1238 values.push(value);
1239 }
1240 Ok(OrderedJsonValue::Array(values))
1241 }
1242
1243 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1244 where
1245 A: MapAccess<'de>,
1246 {
1247 let mut entries = Vec::new();
1248 while let Some((key, value)) = map.next_entry()? {
1249 entries.push((key, value));
1250 }
1251 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1252 }
1253 }
1254
1255 deserializer.deserialize_any(OrderedValueVisitor)
1256 }
1257}
1258
1259impl Serialize for OrderedJsonObject {
1260 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1261 where
1262 S: Serializer,
1263 {
1264 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1265 for (key, value) in &self.0 {
1266 map.serialize_entry(key, value)?;
1267 }
1268 map.end()
1269 }
1270}
1271
1272impl<'de> Deserialize<'de> for OrderedJsonObject {
1273 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1274 where
1275 D: Deserializer<'de>,
1276 {
1277 struct OrderedObjectVisitor;
1278
1279 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1280 type Value = OrderedJsonObject;
1281
1282 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1283 formatter.write_str("an object with ordered JSON members")
1284 }
1285
1286 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1287 where
1288 A: MapAccess<'de>,
1289 {
1290 let mut entries = Vec::new();
1291 while let Some((key, value)) = map.next_entry()? {
1292 entries.push((key, value));
1293 }
1294 Ok(OrderedJsonObject(entries))
1295 }
1296 }
1297
1298 deserializer.deserialize_map(OrderedObjectVisitor)
1299 }
1300}
1301
1302fn read_tagged<'de, D>(
1303 deserializer: D,
1304 field: &'static str,
1305) -> Result<(String, OrderedJsonObject), D::Error>
1306where
1307 D: Deserializer<'de>,
1308{
1309 let body = OrderedJsonObject::deserialize(deserializer)?;
1310 let mut tag = None;
1311 for (key, value) in body.as_entries() {
1312 if key != field {
1313 continue;
1314 }
1315 if tag.is_some() {
1316 return Err(D::Error::custom(format!(
1317 "tagged object has duplicate `{field}` field"
1318 )));
1319 }
1320 let OrderedJsonValue::String(value) = value else {
1321 return Err(D::Error::custom(format!(
1322 "tagged object has no string `{field}` field"
1323 )));
1324 };
1325 tag = Some(value);
1326 }
1327 let Some(tag) = tag else {
1328 return Err(D::Error::custom(format!(
1329 "tagged object has no string `{field}` field"
1330 )));
1331 };
1332 Ok((tag.to_string(), body))
1333}
1334
1335fn read_ordered_tagged(
1336 value: OrderedJsonValue,
1337 field: &'static str,
1338) -> Result<(String, OrderedJsonObject), String> {
1339 let OrderedJsonValue::Object(body) = value else {
1340 return Err(format!("expected tagged object with `{field}` field"));
1341 };
1342 let mut tag = None;
1343 for (key, value) in body.as_entries() {
1344 if key != field {
1345 continue;
1346 }
1347 if tag.is_some() {
1348 return Err(format!("tagged object has duplicate `{field}` field"));
1349 }
1350 let OrderedJsonValue::String(value) = value else {
1351 return Err(format!("tagged object has no string `{field}` field"));
1352 };
1353 tag = Some(value);
1354 }
1355 let Some(tag) = tag else {
1356 return Err(format!("tagged object has no string `{field}` field"));
1357 };
1358 Ok((tag.to_string(), body))
1359}
1360
1361fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1362 body.as_entries()
1363 .iter()
1364 .find_map(|(key, value)| (key == field).then_some(value))
1365}
1366
1367fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1368 match ordered_field(body, field) {
1369 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1370 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1371 None => Err(format!("tagged object has no `{field}` field")),
1372 }
1373}
1374
1375fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1376 let (tag, body) = read_ordered_tagged(value, "method")?;
1377 match tag.as_str() {
1378 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1379 digest: ordered_string(&body, "digest")?,
1380 }),
1381 "macos_spawn_inode" => {
1382 let device = ordered_field(&body, "device")
1383 .and_then(|value| match value {
1384 OrderedJsonValue::Number(number) => number.as_u64(),
1385 _ => None,
1386 })
1387 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1388 let inode = ordered_field(&body, "inode")
1389 .and_then(|value| match value {
1390 OrderedJsonValue::Number(number) => number.as_u64(),
1391 _ => None,
1392 })
1393 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1394 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1395 }
1396 "windows_spawn_file_id" => {
1397 let wire: RunningImageEvidenceWire = serde_json::from_value(
1398 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1399 )
1400 .map_err(|error| error.to_string())?;
1401 match wire {
1402 RunningImageEvidenceWire::WindowsSpawnFileId {
1403 volume_serial_number,
1404 file_id,
1405 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1406 volume_serial_number,
1407 file_id,
1408 }),
1409 _ => unreachable!(),
1410 }
1411 }
1412 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1413 }
1414}
1415
1416impl Serialize for ModuleDeclaredProvenance {
1417 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1418 where
1419 S: Serializer,
1420 {
1421 match self {
1422 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1423 build: build.clone(),
1424 }
1425 .serialize(serializer),
1426 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1427 Self::Unknown { body, .. } => body.serialize(serializer),
1428 }
1429 }
1430}
1431
1432impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1433 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1434 where
1435 D: serde::Deserializer<'de>,
1436 {
1437 let (tag, value) = read_tagged(deserializer, "status")?;
1438 match tag.as_str() {
1439 "reported" => match serde_json::from_value(value.into_value())
1440 .map_err(D::Error::custom)?
1441 {
1442 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1443 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1444 },
1445 "unverifiable" => {
1446 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1447 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1448 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1449 }
1450 }
1451 _ => Ok(Self::Unknown { tag, body: value }),
1452 }
1453 }
1454}
1455
1456impl Serialize for RunningImageAgreement {
1457 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1458 where
1459 S: Serializer,
1460 {
1461 match self {
1462 Self::Match { evidence } => RunningImageAgreementWire::Match {
1463 evidence: evidence.clone(),
1464 }
1465 .serialize(serializer),
1466 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1467 running: running.clone(),
1468 disk: disk.clone(),
1469 }
1470 .serialize(serializer),
1471 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1472 reason: reason.clone(),
1473 }
1474 .serialize(serializer),
1475 Self::Unknown { body, .. } => body.serialize(serializer),
1476 }
1477 }
1478}
1479
1480impl Serialize for ReloadPathAgreement {
1481 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1482 where
1483 S: Serializer,
1484 {
1485 match self {
1486 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1487 Self::Mismatch {
1488 configured,
1489 spawned_from,
1490 } => ReloadPathAgreementWire::Mismatch {
1491 configured: configured.clone(),
1492 spawned_from: spawned_from.clone(),
1493 }
1494 .serialize(serializer),
1495 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1496 reason: reason.clone(),
1497 }
1498 .serialize(serializer),
1499 Self::Unknown { body, .. } => body.serialize(serializer),
1500 }
1501 }
1502}
1503
1504impl Serialize for LaunchSpecAgreement {
1505 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1506 where
1507 S: Serializer,
1508 {
1509 match self {
1510 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1511 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1512 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1513 reason: reason.clone(),
1514 }
1515 .serialize(serializer),
1516 Self::Unknown { body, .. } => body.serialize(serializer),
1517 }
1518 }
1519}
1520
1521impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1522 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1523 where
1524 D: Deserializer<'de>,
1525 {
1526 let (tag, body) = read_tagged(deserializer, "status")?;
1527 match tag.as_str() {
1528 "match" => Ok(Self::Match),
1529 "mismatch" => Ok(Self::Mismatch),
1530 "unavailable" => match serde_json::from_value(body.into_value())
1531 .map_err(D::Error::custom)?
1532 {
1533 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1534 _ => unreachable!(),
1535 },
1536 _ => Ok(Self::Unknown { tag, body }),
1537 }
1538 }
1539}
1540
1541impl<'de> Deserialize<'de> for ReloadPathAgreement {
1542 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1543 where
1544 D: Deserializer<'de>,
1545 {
1546 let (tag, body) = read_tagged(deserializer, "status")?;
1547 match tag.as_str() {
1548 "match" => Ok(Self::Match),
1549 "mismatch" => {
1550 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1551 ReloadPathAgreementWire::Mismatch {
1552 configured,
1553 spawned_from,
1554 } => Ok(Self::Mismatch {
1555 configured,
1556 spawned_from,
1557 }),
1558 _ => unreachable!(),
1559 }
1560 }
1561 "unavailable" => match serde_json::from_value(body.into_value())
1562 .map_err(D::Error::custom)?
1563 {
1564 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1565 _ => unreachable!(),
1566 },
1567 _ => Ok(Self::Unknown { tag, body }),
1568 }
1569 }
1570}
1571
1572impl<'de> Deserialize<'de> for RunningImageAgreement {
1573 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1574 where
1575 D: serde::Deserializer<'de>,
1576 {
1577 let (tag, value) = read_tagged(deserializer, "status")?;
1578 match tag.as_str() {
1579 "match" => Ok(Self::Match {
1580 evidence: decode_running_image_evidence(
1581 ordered_field(&value, "evidence")
1582 .cloned()
1583 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1584 )
1585 .map_err(D::Error::custom)?,
1586 }),
1587 "mismatch" => Ok(Self::Mismatch {
1588 running: decode_running_image_evidence(
1589 ordered_field(&value, "running")
1590 .cloned()
1591 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1592 )
1593 .map_err(D::Error::custom)?,
1594 disk: decode_running_image_evidence(
1595 ordered_field(&value, "disk")
1596 .cloned()
1597 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1598 )
1599 .map_err(D::Error::custom)?,
1600 }),
1601 "unavailable" => Ok(Self::Unavailable {
1602 reason: serde_json::from_value(
1603 ordered_field(&value, "reason")
1604 .cloned()
1605 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1606 .into_value(),
1607 )
1608 .map_err(D::Error::custom)?,
1609 }),
1610 _ => Ok(Self::Unknown { tag, body: value }),
1611 }
1612 }
1613}
1614
1615impl Serialize for ChildResourceUsage {
1616 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1617 where
1618 S: Serializer,
1619 {
1620 match self {
1621 Self::Measured(reading) => {
1622 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1623 }
1624 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1625 reason: reason.clone(),
1626 }
1627 .serialize(serializer),
1628 Self::Unknown { body, .. } => body.serialize(serializer),
1629 }
1630 }
1631}
1632
1633impl<'de> Deserialize<'de> for ChildResourceUsage {
1634 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1635 where
1636 D: Deserializer<'de>,
1637 {
1638 let (tag, body) = read_tagged(deserializer, "status")?;
1639 match tag.as_str() {
1640 "measured" | "unavailable" => {
1641 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1642 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1643 ChildResourceUsageWire::Unavailable { reason } => {
1644 Ok(Self::Unavailable { reason })
1645 }
1646 }
1647 }
1648 _ => Ok(Self::Unknown { tag, body }),
1649 }
1650 }
1651}
1652
1653impl Serialize for RunningImageEvidence {
1654 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1655 where
1656 S: Serializer,
1657 {
1658 match self {
1659 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1660 digest: digest.clone(),
1661 }
1662 .serialize(serializer),
1663 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1664 device: *device,
1665 inode: *inode,
1666 }
1667 .serialize(serializer),
1668 Self::WindowsSpawnFileId {
1669 volume_serial_number,
1670 file_id,
1671 } => RunningImageEvidenceWire::WindowsSpawnFileId {
1672 volume_serial_number: *volume_serial_number,
1673 file_id: *file_id,
1674 }
1675 .serialize(serializer),
1676 Self::Unknown { body, .. } => body.serialize(serializer),
1677 }
1678 }
1679}
1680
1681impl<'de> Deserialize<'de> for RunningImageEvidence {
1682 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1683 where
1684 D: serde::Deserializer<'de>,
1685 {
1686 let (tag, value) = read_tagged(deserializer, "method")?;
1687 match tag.as_str() {
1688 "linux_proc_sha256" => {
1689 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1690 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1691 Ok(Self::LinuxProcSha256 { digest })
1692 }
1693 _ => unreachable!(),
1694 }
1695 }
1696 "macos_spawn_inode" => {
1697 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1698 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1699 Ok(Self::MacosSpawnInode { device, inode })
1700 }
1701 _ => unreachable!(),
1702 }
1703 }
1704 "windows_spawn_file_id" => {
1705 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1706 RunningImageEvidenceWire::WindowsSpawnFileId {
1707 volume_serial_number,
1708 file_id,
1709 } => Ok(Self::WindowsSpawnFileId {
1710 volume_serial_number,
1711 file_id,
1712 }),
1713 _ => unreachable!(),
1714 }
1715 }
1716 _ => Ok(Self::Unknown { tag, body: value }),
1717 }
1718 }
1719}
1720
1721impl Serialize for SupervisorRouteConsumer {
1722 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1723 where
1724 S: Serializer,
1725 {
1726 match self {
1727 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1728 module_id: module_id.clone(),
1729 }
1730 .serialize(serializer),
1731 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1732 connection_id: *connection_id,
1733 }
1734 .serialize(serializer),
1735 Self::Unknown { body, .. } => body.serialize(serializer),
1736 }
1737 }
1738}
1739
1740impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1741 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1742 where
1743 D: serde::Deserializer<'de>,
1744 {
1745 let (tag, value) = read_tagged(deserializer, "kind")?;
1746 match tag.as_str() {
1747 "reserved" => {
1748 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1749 SupervisorRouteConsumerWire::Reserved { module_id } => {
1750 Ok(Self::Reserved { module_id })
1751 }
1752 _ => unreachable!(),
1753 }
1754 }
1755 "direct" => {
1756 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1757 SupervisorRouteConsumerWire::Direct { connection_id } => {
1758 Ok(Self::Direct { connection_id })
1759 }
1760 _ => unreachable!(),
1761 }
1762 }
1763 _ => Ok(Self::Unknown { tag, body: value }),
1764 }
1765 }
1766}
1767
1768impl Serialize for StderrCaptureState {
1769 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1770 where
1771 S: Serializer,
1772 {
1773 match self {
1774 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1775 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1776 reason: reason.clone(),
1777 }
1778 .serialize(serializer),
1779 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1780 reason: reason.clone(),
1781 }
1782 .serialize(serializer),
1783 Self::Unknown { body, .. } => body.serialize(serializer),
1784 }
1785 }
1786}
1787
1788impl<'de> Deserialize<'de> for StderrCaptureState {
1789 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1790 where
1791 D: serde::Deserializer<'de>,
1792 {
1793 let (tag, value) = read_tagged(deserializer, "state")?;
1794 match tag.as_str() {
1795 "captured" => {
1796 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1797 StderrCaptureStateWire::Captured => Ok(Self::Captured),
1798 _ => unreachable!(),
1799 }
1800 }
1801 "incomplete" => match serde_json::from_value(value.into_value())
1802 .map_err(D::Error::custom)?
1803 {
1804 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1805 _ => unreachable!(),
1806 },
1807 "not_captured" => match serde_json::from_value(value.into_value())
1808 .map_err(D::Error::custom)?
1809 {
1810 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1811 _ => unreachable!(),
1812 },
1813 _ => Ok(Self::Unknown { tag, body: value }),
1814 }
1815 }
1816}
1817
1818impl Serialize for StderrTailEntry {
1819 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1820 where
1821 S: Serializer,
1822 {
1823 match self {
1824 Self::Line {
1825 text,
1826 truncated,
1827 at_ms,
1828 } => StderrTailEntryWire::Line {
1829 text: text.clone(),
1830 truncated: *truncated,
1831 at_ms: *at_ms,
1832 }
1833 .serialize(serializer),
1834 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1835 Self::Unknown { body, .. } => body.serialize(serializer),
1836 }
1837 }
1838}
1839
1840impl<'de> Deserialize<'de> for StderrTailEntry {
1841 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1842 where
1843 D: serde::Deserializer<'de>,
1844 {
1845 let (tag, value) = read_tagged(deserializer, "kind")?;
1846 match tag.as_str() {
1847 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1848 StderrTailEntryWire::Line {
1849 text,
1850 truncated,
1851 at_ms,
1852 } => Ok(Self::Line {
1853 text,
1854 truncated,
1855 at_ms,
1856 }),
1857 _ => unreachable!(),
1858 },
1859 "process_start" => {
1860 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1861 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1862 _ => unreachable!(),
1863 }
1864 }
1865 _ => Ok(Self::Unknown { tag, body: value }),
1866 }
1867 }
1868}
1869
1870fn is_zero_u64(value: &u64) -> bool {
1871 *value == 0
1872}
1873
1874fn default_true() -> bool {
1875 true
1876}
1877
1878#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1880pub struct TerminalHistory {
1881 pub daemon_started_at_ms: u64,
1883 pub entries: Vec<TerminalEntry>,
1884 #[serde(default, skip_serializing_if = "is_zero_u64")]
1887 pub dropped: u64,
1888 #[serde(default, skip_serializing_if = "is_zero_u64")]
1891 pub journal_skipped_lines: u64,
1892 #[serde(default, skip_serializing_if = "is_zero_u64")]
1894 pub journal_read_errors: u64,
1895 #[serde(default, skip_serializing_if = "is_zero_u64")]
1897 pub journal_write_failures: u64,
1898}
1899
1900#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1902pub struct TerminalEntry {
1903 #[serde(default, skip_serializing_if = "Option::is_none")]
1906 pub daemon_incarnation: Option<String>,
1907 #[serde(default, skip_serializing_if = "Option::is_none")]
1908 pub exit_code: Option<i32>,
1909 #[serde(default, skip_serializing_if = "Option::is_none")]
1910 pub exit_signal: Option<i32>,
1911 pub at_ms: u64,
1912 pub disposition: TerminalDisposition,
1913 #[serde(default, skip_serializing_if = "Option::is_none")]
1917 pub exit_kind: Option<TerminalExitKind>,
1918 #[serde(default, skip_serializing_if = "Option::is_none")]
1925 pub disposition_detail: Option<String>,
1926}
1927
1928#[derive(Debug, Clone, PartialEq, Eq)]
1933pub enum TerminalExitKind {
1934 Clean,
1935 Crash,
1936 DeliberateSeverance,
1937 Unknown(String),
1938}
1939
1940impl TerminalExitKind {
1941 fn wire_name(&self) -> &str {
1942 match self {
1943 Self::Clean => "clean",
1944 Self::Crash => "crash",
1945 Self::DeliberateSeverance => "deliberate_severance",
1946 Self::Unknown(value) => value,
1947 }
1948 }
1949}
1950
1951impl Serialize for TerminalExitKind {
1952 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1953 where
1954 S: serde::Serializer,
1955 {
1956 serializer.serialize_str(self.wire_name())
1957 }
1958}
1959
1960impl<'de> Deserialize<'de> for TerminalExitKind {
1961 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1962 where
1963 D: serde::Deserializer<'de>,
1964 {
1965 let value = String::deserialize(deserializer)?;
1966 Ok(match value.as_str() {
1967 "clean" => Self::Clean,
1968 "crash" => Self::Crash,
1969 "deliberate_severance" => Self::DeliberateSeverance,
1970 _ => Self::Unknown(value),
1971 })
1972 }
1973}
1974
1975open_string_enum! {
1976 TerminalDisposition {
1978 Stopped => "stopped",
1979 Disabled => "disabled",
1980 Failed => "failed",
1981 Restarting => "restarting",
1982 DaemonShutdown => "daemon_shutdown",
1987 }
1988}
1989
1990#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1991#[serde(rename_all = "snake_case")]
1992pub enum PollKind {
1993 Status,
1994 Liveness,
1995}
1996
1997#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2009#[non_exhaustive]
2010pub struct CatalogEntry {
2011 pub module_id: String,
2012 #[serde(default, skip_serializing_if = "Option::is_none")]
2014 pub display_name: Option<String>,
2015 #[serde(default = "default_true")]
2026 pub ready: bool,
2027 #[serde(default, skip_serializing_if = "Option::is_none")]
2031 pub not_ready: Option<NotReadyReason>,
2032 #[serde(default, skip_serializing_if = "Option::is_none")]
2053 pub module_version: Option<String>,
2054 #[serde(default, skip_serializing_if = "Option::is_none")]
2057 pub provenance: Option<ManifestProvenance>,
2058 pub roles: Vec<ProviderRole>,
2059 pub control_ops: Vec<String>,
2060 #[serde(default, skip_serializing_if = "Option::is_none")]
2065 pub capabilities: Option<CapabilityDeclarations>,
2066 #[serde(default, skip_serializing_if = "Option::is_none")]
2069 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2070 #[serde(default, skip_serializing_if = "Option::is_none")]
2074 pub events: Option<Vec<EventDeclaration>>,
2075 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2078 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2079 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2082 pub operation_payload: BTreeMap<String, OperationPayload>,
2083 #[serde(default, skip_serializing_if = "Option::is_none")]
2089 pub flow_operations: Option<Vec<String>>,
2090 #[serde(default, skip_serializing_if = "Option::is_none")]
2096 pub confirm_operations: Option<Vec<String>>,
2097 #[serde(default, skip_serializing_if = "Option::is_none")]
2100 pub rich_ui: Option<RichUiDescriptor>,
2101 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2104 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2105 #[serde(default, skip_serializing_if = "is_false")]
2108 pub nonce_verified: bool,
2109}
2110
2111impl CatalogEntry {
2112 #[must_use]
2114 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2115 self.display_name = display_name;
2116 self
2117 }
2118
2119 #[must_use]
2121 pub fn new(
2122 module_id: impl Into<String>,
2123 roles: Vec<ProviderRole>,
2124 control_ops: Vec<String>,
2125 ) -> Self {
2126 Self {
2127 module_id: module_id.into(),
2128 ready: default_true(),
2129 display_name: None,
2130 not_ready: None,
2131 module_version: None,
2132 provenance: None,
2133 roles,
2134 control_ops,
2135 capabilities: None,
2136 self_signals: None,
2137 events: None,
2138 operation_delivery: BTreeMap::new(),
2139 operation_payload: BTreeMap::new(),
2140 flow_operations: None,
2141 confirm_operations: None,
2142 rich_ui: None,
2143 role_declarations: BTreeMap::new(),
2144 nonce_verified: false,
2145 }
2146 }
2147
2148 #[must_use]
2150 pub fn with_operation_payload(
2151 mut self,
2152 operation_payload: BTreeMap<String, OperationPayload>,
2153 ) -> Self {
2154 self.operation_payload = operation_payload;
2155 self
2156 }
2157
2158 #[must_use]
2161 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2162 self.flow_operations = flow_operations;
2163 self
2164 }
2165
2166 #[must_use]
2169 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2170 self.confirm_operations = confirm_operations;
2171 self
2172 }
2173
2174 #[must_use]
2176 pub fn with_ready(mut self, ready: bool) -> Self {
2177 self.ready = ready;
2178 self
2179 }
2180
2181 #[must_use]
2183 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2184 self.not_ready = not_ready;
2185 self
2186 }
2187
2188 #[must_use]
2190 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2191 self.module_version = module_version;
2192 self
2193 }
2194
2195 #[must_use]
2197 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2198 self.provenance = provenance;
2199 self
2200 }
2201
2202 #[must_use]
2204 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2205 self.capabilities = capabilities;
2206 self
2207 }
2208
2209 #[must_use]
2211 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2212 self.self_signals = self_signals;
2213 self
2214 }
2215
2216 #[must_use]
2218 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2219 self.events = events;
2220 self
2221 }
2222
2223 #[must_use]
2226 pub fn with_operation_delivery(
2227 mut self,
2228 operation_delivery: BTreeMap<String, OperationDelivery>,
2229 ) -> Self {
2230 self.operation_delivery = operation_delivery;
2231 self
2232 }
2233
2234 #[must_use]
2236 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2237 self.rich_ui = rich_ui;
2238 self
2239 }
2240
2241 #[must_use]
2243 pub fn with_role_declarations(
2244 mut self,
2245 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2246 ) -> Self {
2247 self.role_declarations = role_declarations;
2248 self
2249 }
2250
2251 #[must_use]
2254 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2255 self.nonce_verified = nonce_verified;
2256 self
2257 }
2258}
2259
2260fn is_false(value: &bool) -> bool {
2261 !value
2262}
2263
2264#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2266pub struct NotReadyReason {
2267 pub reason: String,
2272 #[serde(default, skip_serializing_if = "Option::is_none")]
2275 pub capability: Option<String>,
2276}
2277
2278impl NotReadyReason {
2279 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2280 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2281}
2282
2283#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2284pub struct CapabilityRequirementStatus {
2285 pub consumer: String,
2286 pub capability: String,
2287 pub need: String,
2288 pub verdict: String,
2289 pub episode_seq: u64,
2290 pub config_satisfiable: bool,
2291 pub runtime_available: bool,
2292 pub detail: String,
2293}
2294
2295#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2296pub struct SupervisorRescanResult {
2297 pub added: Vec<String>,
2298 pub removed: Vec<String>,
2299 pub changed_pending_reload: Vec<String>,
2300 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2313 pub enabled_changes: Vec<String>,
2314 pub unchanged: u32,
2315 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2323 pub preview: bool,
2324 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2342 pub restart_required: Vec<String>,
2343 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2347 pub capability_warnings: Vec<String>,
2348 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2355 pub module_actions: Vec<RescanModuleAction>,
2356 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2360 pub earlier_pending: Vec<String>,
2361 #[serde(default, skip_serializing_if = "Option::is_none")]
2364 pub expect: Option<RescanExpect>,
2365}
2366
2367#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2383#[serde(rename_all = "snake_case")]
2384pub enum ModuleProtocol {
2385 #[default]
2389 Subc,
2390 None,
2399}
2400
2401#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2413#[non_exhaustive]
2414pub struct SupervisorEntry {
2415 #[serde(default, skip_serializing_if = "Option::is_none")]
2418 pub waiting_for_previous_pid: Option<u32>,
2419 pub module_id: String,
2420 pub state: String,
2421 #[serde(default, skip_serializing_if = "Option::is_none")]
2425 pub next_retry_at_ms: Option<u64>,
2426 pub enabled: bool,
2427 #[serde(default, skip_serializing_if = "Option::is_none")]
2430 pub configured_enabled: Option<bool>,
2431 pub live: bool,
2441 #[serde(default)]
2445 pub protocol: ModuleProtocol,
2446 #[serde(default, skip_serializing_if = "Option::is_none")]
2449 pub launch_nonce_env: Option<bool>,
2450 #[serde(default, skip_serializing_if = "Option::is_none")]
2456 pub launch_nonce_source: Option<String>,
2457 pub health: SupervisorHealthStatus,
2458 #[serde(default, skip_serializing_if = "Option::is_none")]
2461 pub pending_reload: Option<PendingReloadVerdict>,
2462 #[serde(default)]
2468 pub last_probe_ms: Option<u64>,
2469 #[serde(default, skip_serializing_if = "Option::is_none")]
2473 pub last_exit_code: Option<i32>,
2474 #[serde(default, skip_serializing_if = "Option::is_none")]
2478 pub last_exit_signal: Option<i32>,
2479 #[serde(default, skip_serializing_if = "Option::is_none")]
2483 pub last_exit_ms: Option<u64>,
2484 #[serde(default, skip_serializing_if = "Option::is_none")]
2487 pub last_exit_kind: Option<TerminalExitKind>,
2488 #[serde(default, skip_serializing_if = "Option::is_none")]
2505 pub restart_count: Option<u32>,
2506 #[serde(default, skip_serializing_if = "Option::is_none")]
2509 pub max_restarts: Option<u32>,
2510 #[serde(default, skip_serializing_if = "Option::is_none")]
2513 pub lifetime_restarts: Option<u32>,
2514 #[serde(default, skip_serializing_if = "Option::is_none")]
2518 pub spawn_generation: Option<u64>,
2519 #[serde(default, skip_serializing_if = "Option::is_none")]
2529 pub restart_window_secs: Option<u64>,
2530 #[serde(default, skip_serializing_if = "Option::is_none")]
2534 pub drain_timeout_ms: Option<u64>,
2535 #[serde(default, skip_serializing_if = "Option::is_none")]
2538 pub restart_backoff_ms: Option<u64>,
2539 #[serde(default, skip_serializing_if = "Option::is_none")]
2542 pub restart_max_backoff_ms: Option<u64>,
2543 #[serde(default, skip_serializing_if = "Option::is_none")]
2556 pub resources: Option<ChildResourceUsage>,
2557 #[serde(default, skip_serializing_if = "Option::is_none")]
2559 pub tree: Option<TreeReading>,
2560 #[serde(default, skip_serializing_if = "Option::is_none")]
2564 pub tree_unavailable: Option<String>,
2565 #[serde(default, skip_serializing_if = "Option::is_none")]
2567 pub cpu_last_hour: Option<CpuLastHour>,
2568}
2569
2570impl SupervisorEntry {
2571 #[must_use]
2573 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2574 self.next_retry_at_ms = next_retry_at_ms;
2575 self
2576 }
2577
2578 #[must_use]
2580 pub fn new(
2581 module_id: impl Into<String>,
2582 state: impl Into<String>,
2583 enabled: bool,
2584 live: bool,
2585 health: SupervisorHealthStatus,
2586 ) -> Self {
2587 Self {
2588 module_id: module_id.into(),
2589 state: state.into(),
2590 next_retry_at_ms: None,
2591 waiting_for_previous_pid: None,
2592 enabled,
2593 configured_enabled: None,
2594 live,
2595 protocol: ModuleProtocol::default(),
2596 launch_nonce_env: None,
2597 launch_nonce_source: None,
2598 health,
2599 pending_reload: None,
2600 last_probe_ms: None,
2601 last_exit_code: None,
2602 last_exit_signal: None,
2603 last_exit_ms: None,
2604 last_exit_kind: None,
2605 restart_count: None,
2606 max_restarts: None,
2607 lifetime_restarts: None,
2608 spawn_generation: None,
2609 restart_window_secs: None,
2610 drain_timeout_ms: None,
2611 restart_backoff_ms: None,
2612 restart_max_backoff_ms: None,
2613 resources: None,
2614 tree: None,
2615 tree_unavailable: None,
2616 cpu_last_hour: None,
2617 }
2618 }
2619
2620 #[must_use]
2622 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2623 self.protocol = protocol;
2624 self
2625 }
2626
2627 #[must_use]
2629 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2630 self.configured_enabled = configured_enabled;
2631 self
2632 }
2633
2634 #[must_use]
2636 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2637 self.launch_nonce_env = launch_nonce_env;
2638 self
2639 }
2640
2641 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2642 self.launch_nonce_source = source;
2643 self
2644 }
2645
2646 #[must_use]
2647 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2648 self.waiting_for_previous_pid = pid;
2649 self
2650 }
2651
2652 #[must_use]
2654 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2655 self.pending_reload = pending_reload;
2656 self
2657 }
2658
2659 #[must_use]
2661 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2662 self.last_probe_ms = last_probe_ms;
2663 self
2664 }
2665
2666 #[must_use]
2668 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2669 self.last_exit_code = last_exit_code;
2670 self
2671 }
2672
2673 #[must_use]
2675 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2676 self.last_exit_signal = last_exit_signal;
2677 self
2678 }
2679
2680 #[must_use]
2682 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2683 self.last_exit_ms = last_exit_ms;
2684 self
2685 }
2686
2687 #[must_use]
2689 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2690 self.last_exit_kind = last_exit_kind;
2691 self
2692 }
2693
2694 #[must_use]
2696 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2697 self.restart_count = restart_count;
2698 self
2699 }
2700
2701 #[must_use]
2703 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2704 self.max_restarts = max_restarts;
2705 self
2706 }
2707
2708 #[must_use]
2710 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2711 self.lifetime_restarts = lifetime_restarts;
2712 self
2713 }
2714
2715 #[must_use]
2717 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2718 self.spawn_generation = spawn_generation;
2719 self
2720 }
2721
2722 #[must_use]
2724 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2725 self.restart_window_secs = restart_window_secs;
2726 self
2727 }
2728
2729 #[must_use]
2731 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2732 self.drain_timeout_ms = drain_timeout_ms;
2733 self
2734 }
2735
2736 #[must_use]
2738 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2739 self.restart_backoff_ms = restart_backoff_ms;
2740 self
2741 }
2742
2743 #[must_use]
2745 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2746 self.restart_max_backoff_ms = restart_max_backoff_ms;
2747 self
2748 }
2749
2750 #[must_use]
2752 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2753 self.resources = resources;
2754 self
2755 }
2756
2757 #[must_use]
2759 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
2760 self.tree = tree;
2761 self
2762 }
2763
2764 #[must_use]
2766 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
2767 self.tree_unavailable = reason;
2768 self
2769 }
2770}
2771
2772#[derive(Debug, Clone, PartialEq)]
2775pub enum ChildResourceUsage {
2776 Measured(ChildResourceReading),
2777 Unavailable {
2778 reason: ChildResourceUnavailableReason,
2779 },
2780 Unknown {
2783 tag: String,
2784 body: OrderedJsonObject,
2785 },
2786}
2787
2788#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2790pub struct ChildResourceReading {
2791 pub memory_bytes: u64,
2794 pub memory_kind: ChildMemoryKind,
2795 #[serde(default, skip_serializing_if = "Option::is_none")]
2798 pub swap_bytes: Option<u64>,
2799 pub cpu_user_ms: u64,
2803 pub cpu_system_ms: u64,
2806}
2807
2808open_string_enum! {
2809 ChildMemoryKind {
2811 PhysFootprint => "phys_footprint",
2815 ResidentSet => "resident_set",
2818 WindowsWorkingSet => "windows_working_set",
2821 }
2822}
2823
2824open_string_enum! {
2825 ChildResourceUnavailableReason {
2827 NotRunning => "not_running",
2829 UnsupportedPlatform => "unsupported_platform",
2831 Unreadable => "unreadable",
2834 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2837 }
2838}
2839
2840#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2841#[serde(rename_all = "snake_case")]
2842pub enum SupervisorHealthStatus {
2843 Ok,
2844 Degraded,
2845 Failing,
2846 Unresponsive,
2847 Unknown,
2848}
2849
2850#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2851pub struct SupervisorHealthEntry {
2852 pub module_id: String,
2853 pub status: SupervisorHealthStatus,
2854 #[serde(default, skip_serializing_if = "Option::is_none")]
2860 pub detail: Option<String>,
2861 #[serde(default, skip_serializing_if = "Option::is_none")]
2866 pub metrics: Option<serde_json::Value>,
2867 pub consecutive_failures: u32,
2868 #[serde(default)]
2871 pub late_answer_count: u64,
2872 #[serde(default, skip_serializing_if = "Option::is_none")]
2874 pub last_late_answer_latency_ms: Option<u64>,
2875 #[serde(default)]
2880 pub last_action: Option<String>,
2881 #[serde(default)]
2884 pub last_action_ms: Option<u64>,
2885 #[serde(default, skip_serializing_if = "Option::is_none")]
2898 pub last_probe_ms: Option<u64>,
2899}
2900
2901#[cfg(test)]
2902mod tests {
2903 #[test]
2904 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2905 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2906 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2907 assert_eq!(decoded.configured_enabled, None);
2908 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2909 }
2910
2911 #[test]
2912 fn configured_enabled_values_round_trip_in_list() {
2913 for enabled in [false, true] {
2914 let entry = SupervisorEntry::new(
2915 "provider",
2916 "running",
2917 true,
2918 true,
2919 SupervisorHealthStatus::Unknown,
2920 )
2921 .with_configured_enabled(Some(enabled));
2922 let entry_json = serde_json::to_value(&entry).unwrap();
2923 assert_eq!(entry_json["configured_enabled"], enabled);
2924 assert_eq!(
2925 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
2926 entry
2927 );
2928 }
2929 }
2930
2931 #[test]
2932 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2933 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2934 volume_serial_number: u64::MAX,
2935 file_id: [
2936 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2937 ],
2938 };
2939 let agreement = super::RunningImageAgreement::Match { evidence };
2940 let encoded = serde_json::to_string(&agreement).unwrap();
2941 assert!(encoded.contains("windows_spawn_file_id"));
2942 assert_eq!(
2943 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
2944 agreement
2945 );
2946 }
2947
2948 #[test]
2949 fn unix_running_image_evidence_keeps_original_wire_bytes() {
2950 assert_eq!(
2951 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
2952 device: 7,
2953 inode: 11
2954 })
2955 .unwrap(),
2956 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
2957 );
2958 assert_eq!(
2959 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
2960 digest: "abc".to_owned()
2961 })
2962 .unwrap(),
2963 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
2964 );
2965 }
2966 use super::*;
2967 use subc_protocol::{BindIdentity, RouteTarget};
2968
2969 #[test]
2970 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2971 let entry = TerminalEntry {
2972 daemon_incarnation: Some("daemon-before-restart".into()),
2973 exit_code: Some(1),
2974 exit_signal: None,
2975 at_ms: 1_700_000_000_123,
2976 disposition: TerminalDisposition::Restarting,
2977 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2978 disposition_detail: None,
2979 };
2980 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2981 assert_eq!(
2982 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2983 ["exit_kind"],
2984 "deliberate_severance"
2985 );
2986
2987 #[derive(serde::Deserialize)]
2988 struct LegacyTerminalEntry {
2989 exit_code: Option<i32>,
2990 exit_signal: Option<i32>,
2991 at_ms: u64,
2992 disposition: TerminalDisposition,
2993 }
2994
2995 let decoded: LegacyTerminalEntry =
2996 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2997 assert_eq!(decoded.exit_code, Some(1));
2998 assert_eq!(decoded.exit_signal, None);
2999 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3000 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3001
3002 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3003 let future: TerminalEntry =
3004 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3005 assert_eq!(
3006 future.exit_kind,
3007 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3008 );
3009 }
3010
3011 #[test]
3012 fn terminal_incarnation_is_optional_for_older_daemons() {
3013 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3014 "at_ms": 123,
3015 "disposition": "stopped"
3016 }))
3017 .unwrap();
3018 let encoded = serde_json::to_value(&entry).unwrap();
3019 assert_eq!(
3020 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3021 (None, None)
3022 );
3023 }
3024
3025 #[test]
3026 fn route_poll_uses_kind_field() {
3027 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3028 route_channel: 7,
3029 route_epoch: 11,
3030 kind: PollKind::Status,
3031 })
3032 .unwrap();
3033
3034 assert_eq!(body["op"], "route.poll");
3035 assert_eq!(body["route_epoch"], 11);
3036 assert_eq!(body["kind"], "status");
3037 assert!(body.get("op").is_some());
3038 }
3039
3040 #[test]
3041 fn route_open_is_internally_tagged() {
3042 let request = ClientControlRequest::RouteOpen {
3043 busy_refusals: None,
3044 target: RouteTarget::ToolProvider {
3045 module_id: "aft".to_string(),
3046 },
3047 identity: BindIdentity::new("opencode", "session-1"),
3048 consumer_identity: None,
3049 consumer_capabilities: None,
3050 role_versions: None,
3051 admission_facts: None,
3052 scope: None,
3053 };
3054
3055 let body = serde_json::to_value(request).unwrap();
3056 assert_eq!(body["op"], "route.open");
3057 assert_eq!(body["target"]["kind"], "tool_provider");
3058 assert!(body.get("consumer_identity").is_none());
3059 assert!(body.get("consumer_capabilities").is_none());
3060 assert!(body.get("role_versions").is_none());
3061 }
3062
3063 #[test]
3064 fn route_open_without_optional_fields_still_decodes() {
3065 let body = serde_json::json!({
3066 "op": "route.open",
3067 "target": { "kind": "tool_provider", "module_id": "aft" },
3068 "identity": {
3069 "project_root": "/tmp/project",
3070 "harness": "opencode",
3071 "session": "session-1"
3072 }
3073 });
3074
3075 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3076 let ClientControlRequest::RouteOpen {
3077 consumer_identity,
3078 consumer_capabilities,
3079 role_versions,
3080 admission_facts,
3081 ..
3082 } = decoded
3083 else {
3084 panic!("decoded wrong request variant");
3085 };
3086 assert_eq!(consumer_identity, None);
3087 assert_eq!(consumer_capabilities, None);
3088 assert_eq!(role_versions, None);
3089 assert_eq!(admission_facts, None);
3090 }
3091
3092 #[test]
3093 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3094 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3095 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3096 match decoded {
3097 ClientControlPush::RouteClosed {
3098 excluded_subscriptions,
3099 terminal,
3100 ..
3101 } => {
3102 assert_eq!(excluded_subscriptions, 0);
3103 assert_eq!(terminal, None);
3104 }
3105 other => panic!("unexpected push: {other:?}"),
3106 }
3107 assert!(!serde_json::to_string(&decoded)
3108 .unwrap()
3109 .contains("terminal"));
3110 }
3111
3112 #[test]
3113 fn old_route_closed_decoder_ignores_new_terminal_field() {
3114 #[derive(serde::Deserialize)]
3115 #[serde(tag = "op")]
3116 enum LegacyClientControlPush {
3117 #[serde(rename = "route.closed")]
3118 RouteClosed {
3119 module_id: String,
3120 reason: RouteCloseReason,
3121 drained: bool,
3122 abandoned: u32,
3123 },
3124 }
3125
3126 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3127 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3128 match decoded {
3129 LegacyClientControlPush::RouteClosed {
3130 module_id,
3131 reason,
3132 drained,
3133 abandoned,
3134 } => {
3135 assert_eq!(module_id, "aft-tools");
3136 assert_eq!(reason, RouteCloseReason::Crash);
3137 assert!(!drained);
3138 assert_eq!(abandoned, 0);
3139 }
3140 }
3141 }
3142
3143 #[test]
3144 fn supervisor_routes_is_a_control_plane_request() {
3145 let body = serde_json::json!({
3146 "op": "supervisor.routes",
3147 "module_id": "aft"
3148 });
3149
3150 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3151 assert_eq!(serde_json::to_value(request).unwrap(), body);
3152 }
3153
3154 #[test]
3155 fn diagnostic_string_enums_retain_unknown_wire_values() {
3156 let reason: RunningImageUnavailableReason =
3157 serde_json::from_str("\"future_reason\"").unwrap();
3158 let disposition: TerminalDisposition =
3159 serde_json::from_str("\"future_disposition\"").unwrap();
3160
3161 assert_eq!(
3162 reason,
3163 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3164 );
3165 assert_eq!(
3166 disposition,
3167 TerminalDisposition::Unknown("future_disposition".to_string())
3168 );
3169 }
3170
3171 #[test]
3172 fn diagnostic_string_enums_preserve_existing_wire_names() {
3173 let names = [
3174 (RunningImageUnavailableReason::NotRunning, "not_running"),
3175 (
3176 RunningImageUnavailableReason::UnsupportedPlatform,
3177 "unsupported_platform",
3178 ),
3179 (
3180 RunningImageUnavailableReason::RunningExecutableUnreadable,
3181 "running_executable_unreadable",
3182 ),
3183 (
3184 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3185 "running_executable_permission_denied",
3186 ),
3187 (
3188 RunningImageUnavailableReason::ProcessHidden,
3189 "process_hidden",
3190 ),
3191 (
3192 RunningImageUnavailableReason::SpawnedPathUnreadable,
3193 "spawned_path_unreadable",
3194 ),
3195 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3196 (
3197 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3198 "process_identity_unconfirmed",
3199 ),
3200 ];
3201 for (value, expected) in names {
3202 let wire = serde_json::to_string(&value).unwrap();
3203 assert_eq!(wire, format!("\"{expected}\""));
3204 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3205 assert_eq!(decoded, value);
3206 }
3207
3208 for (value, expected) in [
3209 (TerminalDisposition::Stopped, "stopped"),
3210 (TerminalDisposition::Disabled, "disabled"),
3211 (TerminalDisposition::Failed, "failed"),
3212 (TerminalDisposition::Restarting, "restarting"),
3213 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3214 ] {
3215 let wire = serde_json::to_string(&value).unwrap();
3216 assert_eq!(wire, format!("\"{expected}\""));
3217 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3218 assert_eq!(decoded, value);
3219 }
3220 }
3221
3222 #[test]
3223 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3224 let entry = SupervisorEntry::new(
3225 "waiting-module",
3226 "starting",
3227 true,
3228 false,
3229 SupervisorHealthStatus::Unknown,
3230 );
3231 let old_wire = serde_json::to_value(&entry).unwrap();
3232 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3233 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3234 assert_eq!(decoded.waiting_for_previous_pid, None);
3235 let entry = entry.with_waiting_for_previous_pid(Some(42));
3236 let wire = serde_json::to_value(&entry).unwrap();
3237 assert_eq!(wire["waiting_for_previous_pid"], 42);
3238 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3239 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3240 }
3241
3242 #[test]
3243 fn diagnostic_string_enums_reject_non_string_bodies() {
3244 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3245 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3246 }
3247
3248 #[test]
3249 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3250 let body = serde_json::json!({
3251 "op": "supervisor.provenance",
3252 "daemon": {
3253 "daemon_build": {},
3254 "daemon_observed": {
3255 "running_image": {
3256 "status": "unavailable",
3257 "reason": "not_running"
3258 }
3259 }
3260 },
3261 "modules": [
3262 {
3263 "module_id": "future",
3264 "module_declared": { "status": "unverifiable" },
3265 "daemon_observed": {
3266 "running_image": {
3267 "status": "unavailable",
3268 "reason": "future_reason"
3269 }
3270 }
3271 },
3272 {
3273 "module_id": "healthy-a",
3274 "module_declared": { "status": "unverifiable" },
3275 "daemon_observed": {
3276 "running_image": {
3277 "status": "match",
3278 "evidence": {
3279 "method": "linux_proc_sha256",
3280 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3281 }
3282 }
3283 }
3284 },
3285 {
3286 "module_id": "healthy-b",
3287 "module_declared": { "status": "unverifiable" },
3288 "daemon_observed": {
3289 "running_image": {
3290 "status": "unavailable",
3291 "reason": "unsupported_platform"
3292 }
3293 }
3294 }
3295 ]
3296 });
3297
3298 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3299 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3300 panic!("decoded wrong response variant");
3301 };
3302 assert_eq!(modules.len(), 3);
3303 assert_eq!(modules[0].module_id, "future");
3304 assert_eq!(
3305 modules[0].daemon_observed.running_image,
3306 RunningImageAgreement::Unavailable {
3307 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3308 }
3309 );
3310 assert_eq!(modules[1].module_id, "healthy-a");
3311 assert_eq!(modules[2].module_id, "healthy-b");
3312 }
3313
3314 #[test]
3315 fn tagged_unknown_values_retain_tag_and_body() {
3316 macro_rules! assert_unknown_round_trip {
3317 ($ty:ident, $field:literal, $value:expr) => {
3318 let value = $value;
3319 let wire = serde_json::to_string(&value).unwrap();
3320 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3321 match decoded {
3322 $ty::Unknown { tag, body } => {
3323 assert_eq!(tag, value[$field].as_str().unwrap());
3324 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3325 }
3326 _ => panic!("decoded known variant"),
3327 }
3328 };
3329 }
3330
3331 assert_unknown_round_trip!(
3332 ModuleDeclaredProvenance,
3333 "status",
3334 serde_json::json!({"status": "future", "build": {"version": 7}})
3335 );
3336 assert_unknown_round_trip!(
3337 RunningImageAgreement,
3338 "status",
3339 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3340 );
3341 assert_unknown_round_trip!(
3342 RunningImageEvidence,
3343 "method",
3344 serde_json::json!({"method": "future", "digest": "abc"})
3345 );
3346 assert_unknown_round_trip!(
3347 SupervisorRouteConsumer,
3348 "kind",
3349 serde_json::json!({"kind": "future", "module_id": "m"})
3350 );
3351 assert_unknown_round_trip!(
3352 StderrCaptureState,
3353 "state",
3354 serde_json::json!({"state": "future", "reason": "because"})
3355 );
3356 assert_unknown_round_trip!(
3357 StderrTailEntry,
3358 "kind",
3359 serde_json::json!({"kind": "future", "text": "line"})
3360 );
3361 assert_unknown_round_trip!(
3362 ChildResourceUsage,
3363 "status",
3364 serde_json::json!({"status": "future", "memory_bytes": 1})
3365 );
3366 }
3367
3368 #[test]
3369 fn child_resource_usage_round_trips_both_known_states() {
3370 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3371 memory_bytes: 0,
3372 memory_kind: ChildMemoryKind::ResidentSet,
3373 swap_bytes: Some(0),
3374 cpu_user_ms: 0,
3375 cpu_system_ms: 0,
3376 });
3377 let wire = serde_json::to_value(&measured).unwrap();
3378 assert_eq!(
3379 wire,
3380 serde_json::json!({
3381 "status": "measured",
3382 "memory_bytes": 0,
3383 "memory_kind": "resident_set",
3384 "swap_bytes": 0,
3385 "cpu_user_ms": 0,
3386 "cpu_system_ms": 0
3387 })
3388 );
3389 assert_eq!(
3390 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3391 measured
3392 );
3393
3394 let unavailable = ChildResourceUsage::Unavailable {
3395 reason: ChildResourceUnavailableReason::NotRunning,
3396 };
3397 let wire = serde_json::to_value(&unavailable).unwrap();
3398 assert_eq!(
3399 wire,
3400 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3401 );
3402 assert_eq!(
3403 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3404 unavailable
3405 );
3406 }
3407
3408 #[test]
3409 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3410 let stamped: StderrTailEntry = serde_json::from_str(
3414 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3415 )
3416 .unwrap();
3417 assert_eq!(
3418 stamped,
3419 StderrTailEntry::Line {
3420 text: "boom".to_string(),
3421 truncated: true,
3422 at_ms: Some(1_789_801_440_685),
3423 }
3424 );
3425 let unstamped: StderrTailEntry =
3426 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3427 assert_eq!(
3428 unstamped,
3429 StderrTailEntry::Line {
3430 text: "boom".to_string(),
3431 truncated: false,
3432 at_ms: None,
3433 }
3434 );
3435 assert_eq!(
3438 serde_json::to_string(&unstamped).unwrap(),
3439 r#"{"kind":"line","text":"boom"}"#
3440 );
3441 assert_eq!(
3442 serde_json::to_value(&stamped).unwrap()["at_ms"],
3443 serde_json::json!(1_789_801_440_685u64)
3444 );
3445 }
3446
3447 #[test]
3448 fn tagged_unknown_values_round_trip_the_original_json() {
3449 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3450 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3451 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3452 }
3453
3454 #[test]
3455 fn tagged_unknown_values_round_trip_trailing_tag() {
3456 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3457 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3458 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3459
3460 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3461 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3462 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3463 }
3464
3465 #[test]
3466 fn tagged_unknown_values_round_trip_middle_tag() {
3467 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3468 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3469 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3470
3471 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3472 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3473 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3474 }
3475
3476 #[test]
3477 fn tagged_unknown_values_round_trip_deep_payload() {
3478 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3479 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3480 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3481
3482 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3483 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3484 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3485 }
3486
3487 #[test]
3488 fn tagged_unknown_values_reject_non_object_bodies() {
3489 for wire in ["42", r#""future""#, "[]"] {
3490 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3491 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3492 }
3493 }
3494
3495 #[test]
3496 fn duplicate_discriminators_reject_without_panicking() {
3497 assert_eq!(
3498 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3499 .unwrap(),
3500 ModuleDeclaredProvenance::Unverifiable
3501 );
3502 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3503 .unwrap()
3504 {
3505 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3506 _ => panic!("future discriminator decoded as a known variant"),
3507 }
3508
3509 let wires = [
3510 r#"{"status":"reported","status":"unverifiable"}"#,
3511 r#"{"status":"unverifiable","status":"reported"}"#,
3512 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3513 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3514 ];
3515
3516 for wire in wires {
3517 let result =
3518 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3519 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3520 assert!(
3521 result.unwrap().is_err(),
3522 "duplicate discriminator decoded: {wire}"
3523 );
3524 }
3525
3526 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3527 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3528 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3529 assert!(
3530 result.unwrap().is_err(),
3531 "duplicate discriminator decoded: {wire}"
3532 );
3533 }
3534
3535 #[test]
3536 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3537 let known_wire =
3538 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3539 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3540 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3541
3542 for wire in [
3543 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3544 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3545 ] {
3546 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3547 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3548 }
3549
3550 for wire in [
3551 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3552 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3553 ] {
3554 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3555 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3556 }
3557
3558 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3559 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3560 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3561
3562 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3563 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3564 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3565 }
3566
3567 #[test]
3568 fn tagged_unknown_member_does_not_discard_known_siblings() {
3569 let body = serde_json::json!({
3570 "modules": [{
3571 "module_id": "target",
3572 "routes": [
3573 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3574 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3575 ]
3576 }]
3577 });
3578 let decoded: ClientControlResponse = serde_json::from_value(
3579 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3580 )
3581 .unwrap();
3582 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3583 panic!("decoded wrong response variant");
3584 };
3585 assert_eq!(modules[0].routes.len(), 2);
3586 assert_eq!(
3587 modules[0].routes[1].consumer,
3588 SupervisorRouteConsumer::Direct { connection_id: 7 }
3589 );
3590 }
3591}
3592
3593#[cfg(test)]
3594mod launch_nonce_redaction_tests {
3595 use super::*;
3596
3597 const NONCE: &str = "nonce-f00dfeed1234abcd";
3598
3599 fn identity() -> ConsumerIdentity {
3600 ConsumerIdentity {
3601 module_id: "wernicke".to_string(),
3602 launch_nonce: NONCE.to_string(),
3603 }
3604 }
3605
3606 #[test]
3607 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3608 let printed = format!("{:?}", identity());
3609 assert!(printed.contains("wernicke"), "{printed}");
3610 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3611 }
3612
3613 #[test]
3614 fn route_open_request_debug_never_prints_the_nonce() {
3615 let request = ClientControlRequest::RouteOpen {
3616 busy_refusals: None,
3617 target: subc_protocol::RouteTarget::ToolProvider {
3618 module_id: "broca".to_string(),
3619 },
3620 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
3621 consumer_identity: Some(identity()),
3622 consumer_capabilities: None,
3623 role_versions: None,
3624 admission_facts: None,
3625 scope: None,
3626 };
3627 let printed = format!("{request:?}");
3628 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3629 }
3630}