1#![forbid(unsafe_code)]
9
10use std::{collections::BTreeMap, path::PathBuf};
11
12use serde::{
13 de::{Error as _, MapAccess, SeqAccess, Visitor},
14 ser::SerializeMap,
15 Deserialize, Deserializer, Serialize, Serializer,
16};
17use subc_protocol::{
18 manifest::{
19 CapabilityDeclarations, EventDeclaration, ManifestProvenance, OperationDelivery,
20 OperationPayload, ProviderRole, RichUiDescriptor, SelfSignalDeclaration,
21 },
22 scope::ScopeSelector,
23 session::HealthStatus,
24 BindIdentity, RouteTarget,
25};
26
27pub use subc_protocol::RouteCloseReason;
28
29mod activity;
30pub use activity::*;
31
32mod scope_served_by;
33pub use scope_served_by::*;
34
35macro_rules! open_string_enum {
36 (
37 $(#[$meta:meta])*
38 $name:ident {
39 $( $(#[$variant_meta:meta])* $variant:ident => $wire_name:literal ),+ $(,)?
40 }
41 ) => {
42 $(#[$meta])*
43 #[derive(Debug, Clone, PartialEq, Eq)]
44 pub enum $name {
45 $( $(#[$variant_meta])* $variant, )+
46 Unknown(String),
47 }
48
49 impl $name {
50 fn wire_name(&self) -> &str {
51 match self {
52 $( Self::$variant => $wire_name, )+
53 Self::Unknown(value) => value,
54 }
55 }
56 }
57
58 impl Serialize for $name {
59 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
60 where
61 S: serde::Serializer,
62 {
63 serializer.serialize_str(self.wire_name())
64 }
65 }
66
67 impl<'de> Deserialize<'de> for $name {
68 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
69 where
70 D: serde::Deserializer<'de>,
71 {
72 let value = String::deserialize(deserializer)?;
73 Ok(match value.as_str() {
74 $( $wire_name => Self::$variant, )+
75 _ => Self::Unknown(value),
76 })
77 }
78 }
79 };
80}
81
82mod rescan_checked;
83pub use rescan_checked::*;
84
85mod app_open;
86pub use app_open::*;
87
88mod connection_describe;
89pub use connection_describe::*;
90
91mod subtree;
92pub use subtree::*;
93
94#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
96pub struct ConsumerIdentity {
97 pub module_id: String,
98 pub launch_nonce: String,
99}
100
101impl std::fmt::Debug for ConsumerIdentity {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 f.debug_struct("ConsumerIdentity")
108 .field("module_id", &self.module_id)
109 .field(
110 "launch_nonce",
111 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
112 )
113 .finish()
114 }
115}
116
117pub mod ops {
128 pub const SERVER: &str = "server.";
129 pub const CATALOG: &str = "catalog.";
130 pub const ROUTE: &str = "route.";
131 pub const SUPERVISOR: &str = "supervisor.";
132 pub const CONFIG: &str = "config.";
133
134 pub const SERVER_DESCRIBE: &str = "server.describe";
135 pub const DAEMON_SHUTDOWN_INTENT: &str = "daemon.shutdown_intent";
136 pub const CATALOG_LIST: &str = "catalog.list";
137 pub const ROUTE_OPEN: &str = "route.open";
138 pub const ROUTE_POLL: &str = "route.poll";
139 pub const ROUTE_CLOSING: &str = "route.closing";
140 pub const ROUTE_CLOSED: &str = "route.closed";
141 pub const SUPERVISOR_LIST: &str = "supervisor.list";
142 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
143 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
144 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
145 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
146 pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
147 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
148 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
149 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
150 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
151 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
152 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
153 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
154 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
155 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
156 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
157 pub const ACTIVITY_RECORD: &str = "activity.record";
158 pub const ACTIVITY_QUERY: &str = "activity.query";
159 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
160 pub const APP_OPEN: &str = "app.open";
161 pub const CONNECTION_DESCRIBE: &str = "connection.describe";
162}
163
164#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
166#[serde(tag = "op")]
167#[allow(clippy::large_enum_variant)]
170pub enum ClientControlRequest {
171 #[serde(rename = "daemon.shutdown_intent")]
174 DaemonShutdownIntent {
175 #[serde(default)]
176 intent: serde_json::Value,
177 },
178 #[serde(rename = "server.describe")]
179 ServerDescribe {},
180 #[serde(rename = "catalog.list")]
181 CatalogList {
182 #[serde(default)]
187 module_id: Option<String>,
188 },
189 #[serde(rename = "route.open")]
190 RouteOpen {
191 target: RouteTarget,
192 identity: BindIdentity,
193 #[serde(default, skip_serializing_if = "Option::is_none")]
202 consumer_identity: Option<ConsumerIdentity>,
203 #[serde(default, skip_serializing_if = "Option::is_none")]
211 consumer_capabilities: Option<Vec<String>>,
212 #[serde(default, skip_serializing_if = "Option::is_none")]
223 role_versions: Option<BTreeMap<String, String>>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
228 busy_refusals: Option<bool>,
229 #[serde(default, skip_serializing_if = "Option::is_none")]
231 admission_facts: Option<serde_json::Value>,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
239 scope: Option<ScopeSelector>,
240 },
241 #[serde(rename = "route.poll")]
242 RoutePoll {
243 route_channel: u16,
244 route_epoch: u32,
245 kind: PollKind,
246 },
247 #[serde(rename = "supervisor.list")]
248 SupervisorList {},
249 #[serde(rename = "supervisor.spawn_snapshot")]
251 SupervisorSpawnSnapshot {},
252 #[serde(rename = "supervisor.spawn_subscribe")]
268 SupervisorSpawnSubscribe {
269 #[serde(default, skip_serializing_if = "Option::is_none")]
270 since: Option<SpawnCursor>,
271 },
272 #[serde(rename = "supervisor.restart")]
273 SupervisorRestart {
274 module_id: String,
275 #[serde(default, skip_serializing_if = "Option::is_none")]
285 drain_timeout_ms: Option<u64>,
286 },
287 #[serde(rename = "supervisor.swap")]
302 SupervisorSwap {
303 module_id: String,
304 #[serde(default, skip_serializing_if = "Option::is_none")]
307 ready_timeout_ms: Option<u64>,
308 },
309 #[serde(rename = "supervisor.reload")]
310 SupervisorReload { module_id: String },
311 #[serde(rename = "supervisor.rescan")]
312 SupervisorRescan {
313 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
333 preview: bool,
334 },
335 #[serde(rename = "supervisor.rescan_checked")]
359 SupervisorRescanChecked {
360 preview: bool,
361 #[serde(default, skip_serializing_if = "Option::is_none")]
362 candidate: Option<String>,
363 #[serde(default, skip_serializing_if = "Option::is_none")]
364 expect: Option<RescanExpect>,
365 },
366 #[serde(rename = "supervisor.release_reserved")]
370 SupervisorReleaseReserved { module_id: String },
371 #[serde(rename = "supervisor.set_enabled")]
372 SupervisorSetEnabled { module_id: String, enabled: bool },
373 #[serde(rename = "supervisor.health_probe")]
374 SupervisorHealthProbe { module_id: String },
375 #[serde(rename = "supervisor.health")]
376 SupervisorHealth {},
377 #[serde(rename = "supervisor.routes")]
390 SupervisorRoutes {
391 #[serde(default, skip_serializing_if = "Option::is_none")]
392 module_id: Option<String>,
393 },
394 #[serde(rename = "supervisor.provenance")]
397 SupervisorProvenance {
398 #[serde(default, skip_serializing_if = "Option::is_none")]
399 module_id: Option<String>,
400 },
401 #[serde(rename = "supervisor.stderr_tail")]
409 SupervisorStderrTail {
410 module_id: String,
411 #[serde(default, skip_serializing_if = "Option::is_none")]
412 max_lines: Option<u32>,
413 #[serde(default, skip_serializing_if = "Option::is_none")]
414 max_bytes: Option<u32>,
415 },
416 #[serde(rename = "supervisor.terminals")]
429 SupervisorTerminals { module_id: String },
430}
431
432#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
434#[serde(tag = "op")]
435pub enum ClientControlResponse {
436 #[serde(rename = "daemon.shutdown_intent")]
437 DaemonShutdownIntent { intent: String, expires_at_ms: u64 },
438 #[serde(rename = "server.describe")]
439 ServerDescribe {
440 protocol_ver: u8,
441 subc_ops: Vec<String>,
442 capabilities: Vec<String>,
443 connected_clients: u64,
444 #[serde(default, skip_serializing_if = "Option::is_none")]
445 counters: Option<serde_json::Value>,
446 #[serde(default, skip_serializing_if = "Option::is_none")]
453 build_git_sha: Option<String>,
454 #[serde(default, skip_serializing_if = "Option::is_none")]
460 build_lock_digest: Option<String>,
461 #[serde(default, skip_serializing_if = "Vec::is_empty")]
465 capability_requirements: Vec<CapabilityRequirementStatus>,
466 #[serde(default, skip_serializing_if = "Option::is_none")]
471 machine_id: Option<String>,
472 #[serde(default, skip_serializing_if = "Option::is_none")]
481 config_path: Option<PathBuf>,
482 },
483 #[serde(rename = "catalog.list")]
484 CatalogList {
485 generation: u64,
486 modules: Vec<CatalogEntry>,
487 subc_ops: Vec<String>,
488 },
489 #[serde(rename = "route.open")]
490 RouteOpen {
491 route_channel: u16,
492 route_epoch: u32,
493 #[serde(default, skip_serializing_if = "Option::is_none")]
495 request_window: Option<usize>,
496 #[serde(default, skip_serializing_if = "Option::is_none")]
498 watch_window: Option<usize>,
499 },
500 #[serde(rename = "route.poll")]
501 RoutePoll {
502 route_channel: u16,
503 route_epoch: u32,
504 status: Option<String>,
505 live: Option<bool>,
506 },
507 #[serde(rename = "supervisor.list")]
508 SupervisorList {
509 generation: u64,
510 modules: Vec<SupervisorEntry>,
511 },
512 #[serde(rename = "supervisor.spawn_snapshot")]
513 SupervisorSpawnSnapshot {
514 #[serde(flatten)]
515 snapshot: SpawnSnapshot,
516 },
517 #[serde(rename = "supervisor.ack")]
518 SupervisorAck { module_id: String, applied: bool },
519 #[serde(rename = "supervisor.rescan")]
520 SupervisorRescan {
521 #[serde(flatten)]
522 result: SupervisorRescanResult,
523 },
524 #[serde(rename = "supervisor.health_probe")]
525 SupervisorHealthProbe {
526 module_id: String,
527 status: HealthStatus,
528 #[serde(default, skip_serializing_if = "Option::is_none")]
529 detail: Option<String>,
530 #[serde(default, skip_serializing_if = "Option::is_none")]
531 metrics: Option<serde_json::Value>,
532 },
533 #[serde(rename = "supervisor.health")]
534 SupervisorHealth {
535 generation: u64,
536 modules: Vec<SupervisorHealthEntry>,
537 },
538 #[serde(rename = "supervisor.routes")]
539 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
540 #[serde(rename = "supervisor.provenance")]
541 SupervisorProvenance {
542 daemon: SupervisorDaemonProvenance,
543 modules: Vec<SupervisorModuleProvenance>,
544 },
545 #[serde(rename = "supervisor.stderr_tail")]
546 SupervisorStderrTail {
547 module_id: String,
548 #[serde(flatten)]
549 tail: StderrTail,
550 },
551 #[serde(rename = "supervisor.terminals")]
552 SupervisorTerminals {
553 module_id: String,
554 #[serde(flatten)]
555 terminals: TerminalHistory,
556 },
557}
558
559#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
564#[serde(tag = "op")]
565pub enum ClientControlPush {
566 #[serde(rename = "route.closing")]
567 RouteClosing {
568 module_id: String,
569 #[serde(default)]
572 channels: Vec<u16>,
573 reason: RouteCloseReason,
574 },
575 #[serde(rename = "route.closed")]
576 RouteClosed {
577 module_id: String,
578 #[serde(default)]
581 channels: Vec<u16>,
582 reason: RouteCloseReason,
583 drained: bool,
585 abandoned: u32,
588 #[serde(default)]
590 excluded_subscriptions: u32,
591 #[serde(default, skip_serializing_if = "Option::is_none")]
597 terminal: Option<bool>,
598 },
599}
600
601#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
603pub struct SpawnCursor {
604 pub daemon_incarnation: String,
605 pub seq: u64,
606}
607
608#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
610pub struct LiveSpawn {
611 pub module_id: String,
612 pub spawn_generation: u64,
613 pub pid: u32,
614 pub spawned_at_ms: u64,
615}
616
617#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
619pub struct SpawnSnapshot {
620 pub cursor: SpawnCursor,
621 pub ring_bound: u64,
623 pub live: Vec<LiveSpawn>,
624}
625
626#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
628#[serde(rename_all = "snake_case")]
629pub enum SpawnEventKind {
630 Spawned,
631 Exited,
632}
633
634#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
640pub struct SpawnEvent {
641 pub cursor: SpawnCursor,
642 pub kind: SpawnEventKind,
643 pub module_id: String,
644 pub spawn_generation: u64,
645 pub pid: u32,
646 #[serde(default, skip_serializing_if = "Option::is_none")]
647 pub exit_code: Option<i32>,
648 #[serde(default, skip_serializing_if = "Option::is_none")]
649 pub exit_signal: Option<i32>,
650}
651
652#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
654pub struct StderrTail {
655 pub capture: StderrCaptureState,
656 pub entries: Vec<StderrTailEntry>,
657 #[serde(default, skip_serializing_if = "is_zero_u64")]
666 pub dropped_lines: u64,
667}
668
669#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
671pub struct SupervisorRouteModule {
672 pub module_id: String,
673 pub routes: Vec<SupervisorRoute>,
674}
675
676#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
678pub struct SupervisorRoute {
679 pub consumer: SupervisorRouteConsumer,
680 pub age_ms: u64,
682 pub draining: bool,
685 #[serde(default, skip_serializing_if = "Option::is_none")]
691 pub drain_reason: Option<RouteCloseReason>,
692}
693
694#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
696pub struct SupervisorModuleProvenance {
697 pub module_id: String,
698 pub module_declared: ModuleDeclaredProvenance,
699 pub daemon_observed: SupervisorObservedProcess,
700}
701
702#[derive(Debug, Clone, PartialEq)]
704pub enum ModuleDeclaredProvenance {
705 Reported {
706 build: ManifestProvenance,
707 },
708 Unverifiable,
709 Unknown {
712 tag: String,
713 body: OrderedJsonObject,
714 },
715}
716
717#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
722pub struct SupervisorObservedProcess {
723 #[serde(default, skip_serializing_if = "Option::is_none")]
729 pub launch_nonce_source: Option<String>,
730 #[serde(default, skip_serializing_if = "Option::is_none")]
731 pub pid: Option<u32>,
732 #[serde(default, skip_serializing_if = "Option::is_none")]
733 pub spawned_at_ms: Option<u64>,
734 #[serde(default, skip_serializing_if = "Option::is_none")]
735 pub spawned_from: Option<PathBuf>,
736 pub running_image: RunningImageAgreement,
737}
738
739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
742pub struct PendingReloadVerdict {
743 pub path: ReloadPathAgreement,
744 pub image: RunningImageAgreement,
745 #[serde(default, skip_serializing_if = "Option::is_none")]
746 pub spec: Option<LaunchSpecAgreement>,
747}
748
749#[cfg(test)]
750mod launch_spec_wire_tests {
751 use super::*;
752
753 #[test]
754 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
755 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
756 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
757 assert_eq!(parsed.spec, None);
758 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
759 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
760 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
761 assert!(
762 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
763 );
764 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
765 let unavailable = LaunchSpecAgreement::Unavailable {
766 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
767 };
768 let encoded = serde_json::to_string(&unavailable).unwrap();
769 assert_eq!(
770 encoded,
771 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
772 );
773 assert_eq!(
774 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
775 unavailable
776 );
777 }
778}
779
780#[derive(Debug, Clone, PartialEq)]
783pub enum LaunchSpecAgreement {
784 Match,
785 Mismatch,
786 Unavailable {
787 reason: LaunchSpecUnavailableReason,
788 },
789 Unknown {
790 tag: String,
791 body: OrderedJsonObject,
792 },
793}
794
795open_string_enum! {
796 LaunchSpecUnavailableReason {
797 NotRunning => "not_running",
798 SpawnedSpecUnavailable => "spawned_spec_unavailable",
799 }
800}
801
802#[derive(Debug, Clone, PartialEq)]
804pub enum ReloadPathAgreement {
805 Match,
806 Mismatch {
807 configured: PathBuf,
808 spawned_from: PathBuf,
809 },
810 Unavailable {
811 reason: ReloadPathUnavailableReason,
812 },
813 Unknown {
814 tag: String,
815 body: OrderedJsonObject,
816 },
817}
818
819open_string_enum! {
820 ReloadPathUnavailableReason {
822 NotRunning => "not_running",
823 SpawnedPathUnavailable => "spawned_path_unavailable",
824 }
825}
826
827#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
829pub struct SupervisorDaemonProvenance {
830 pub daemon_build: DaemonBuildProvenance,
831 pub daemon_observed: DaemonObservedProcess,
832}
833
834#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
836pub struct DaemonBuildProvenance {
837 #[serde(default, skip_serializing_if = "Option::is_none")]
838 pub build_git_sha: Option<String>,
839 #[serde(default, skip_serializing_if = "Option::is_none")]
840 pub build_lock_digest: Option<String>,
841}
842
843#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
845pub struct DaemonObservedProcess {
846 #[serde(default, skip_serializing_if = "Option::is_none")]
847 pub pid: Option<u32>,
848 #[serde(default, skip_serializing_if = "Option::is_none")]
853 pub started_at_ms: Option<u64>,
854 pub running_image: RunningImageAgreement,
855}
856
857#[derive(Debug, Clone, PartialEq)]
859pub enum RunningImageAgreement {
860 Match {
861 evidence: RunningImageEvidence,
862 },
863 Mismatch {
864 running: RunningImageEvidence,
865 disk: RunningImageEvidence,
866 },
867 Unavailable {
868 reason: RunningImageUnavailableReason,
869 },
870 Unknown {
873 tag: String,
874 body: OrderedJsonObject,
875 },
876}
877
878#[derive(Debug, Clone, PartialEq)]
880pub enum RunningImageEvidence {
881 LinuxProcSha256 {
882 digest: String,
883 },
884 MacosSpawnInode {
885 device: u64,
886 inode: u64,
887 },
888 WindowsSpawnFileId {
890 volume_serial_number: u64,
891 file_id: [u8; 16],
892 },
893 Unknown {
896 tag: String,
897 body: OrderedJsonObject,
898 },
899}
900
901open_string_enum! {
902 RunningImageUnavailableReason {
904 NotRunning => "not_running",
905 UnsupportedPlatform => "unsupported_platform",
906 RunningExecutableUnreadable => "running_executable_unreadable",
907 RunningExecutablePermissionDenied => "running_executable_permission_denied",
908 ProcessHidden => "process_hidden",
909 SpawnedPathUnreadable => "spawned_path_unreadable",
910 HashFailed => "hash_failed",
911 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
912 }
913}
914
915#[derive(Debug, Clone, PartialEq)]
921pub enum SupervisorRouteConsumer {
922 Reserved {
923 module_id: String,
924 },
925 Direct {
926 connection_id: u64,
927 },
928 Unknown {
931 tag: String,
932 body: OrderedJsonObject,
933 },
934}
935
936#[derive(Debug, Clone, PartialEq)]
943pub enum StderrCaptureState {
944 Captured,
947 Incomplete { reason: String },
949 NotCaptured { reason: String },
951 Unknown {
954 tag: String,
955 body: OrderedJsonObject,
956 },
957}
958
959#[derive(Debug, Clone, PartialEq)]
960pub enum StderrTailEntry {
961 Line {
962 text: String,
963 truncated: bool,
968 at_ms: Option<u64>,
972 },
973 ProcessStart,
978 Unknown {
981 tag: String,
982 body: OrderedJsonObject,
983 },
984}
985
986#[derive(Debug, Serialize, Deserialize)]
987#[serde(tag = "status", rename_all = "snake_case")]
988enum ModuleDeclaredProvenanceWire {
989 Reported { build: ManifestProvenance },
990 Unverifiable,
991}
992
993#[derive(Debug, Serialize, Deserialize)]
994#[serde(tag = "status", rename_all = "snake_case")]
995enum RunningImageAgreementWire {
996 Match {
997 evidence: RunningImageEvidence,
998 },
999 Mismatch {
1000 running: RunningImageEvidence,
1001 disk: RunningImageEvidence,
1002 },
1003 Unavailable {
1004 reason: RunningImageUnavailableReason,
1005 },
1006}
1007
1008#[derive(Debug, Serialize, Deserialize)]
1009#[serde(tag = "status", rename_all = "snake_case")]
1010enum ReloadPathAgreementWire {
1011 Match,
1012 Mismatch {
1013 configured: PathBuf,
1014 spawned_from: PathBuf,
1015 },
1016 Unavailable {
1017 reason: ReloadPathUnavailableReason,
1018 },
1019}
1020
1021#[derive(Debug, Serialize, Deserialize)]
1022#[serde(tag = "status", rename_all = "snake_case")]
1023enum LaunchSpecAgreementWire {
1024 Match,
1025 Mismatch,
1026 Unavailable { reason: LaunchSpecUnavailableReason },
1027}
1028
1029#[derive(Debug, Serialize, Deserialize)]
1030#[serde(tag = "method", rename_all = "snake_case")]
1031enum RunningImageEvidenceWire {
1032 LinuxProcSha256 {
1033 digest: String,
1034 },
1035 MacosSpawnInode {
1036 device: u64,
1037 inode: u64,
1038 },
1039 WindowsSpawnFileId {
1040 volume_serial_number: u64,
1041 file_id: [u8; 16],
1042 },
1043}
1044
1045#[derive(Debug, Serialize, Deserialize)]
1046#[serde(tag = "kind", rename_all = "snake_case")]
1047enum SupervisorRouteConsumerWire {
1048 Reserved { module_id: String },
1049 Direct { connection_id: u64 },
1050}
1051
1052#[derive(Debug, Serialize, Deserialize)]
1053#[serde(tag = "state", rename_all = "snake_case")]
1054enum StderrCaptureStateWire {
1055 Captured,
1056 Incomplete { reason: String },
1057 NotCaptured { reason: String },
1058}
1059
1060#[derive(Debug, Serialize, Deserialize)]
1061#[serde(tag = "status", rename_all = "snake_case")]
1062enum ChildResourceUsageWire {
1063 Measured(ChildResourceReading),
1064 Unavailable {
1065 reason: ChildResourceUnavailableReason,
1066 },
1067}
1068
1069#[derive(Debug, Serialize, Deserialize)]
1070#[serde(tag = "kind", rename_all = "snake_case")]
1071enum StderrTailEntryWire {
1072 Line {
1073 text: String,
1074 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1075 truncated: bool,
1076 #[serde(default, skip_serializing_if = "Option::is_none")]
1079 at_ms: Option<u64>,
1080 },
1081 ProcessStart,
1082}
1083
1084#[derive(Debug, Clone, PartialEq)]
1086pub enum OrderedJsonValue {
1087 Null,
1088 Bool(bool),
1089 Number(serde_json::Number),
1090 String(String),
1091 Array(Vec<Self>),
1092 Object(OrderedJsonObject),
1093}
1094
1095#[derive(Debug, Clone, PartialEq)]
1097pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1098
1099impl OrderedJsonObject {
1100 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1102 &self.0
1103 }
1104
1105 fn into_value(self) -> serde_json::Value {
1106 serde_json::Value::Object(
1107 self.0
1108 .into_iter()
1109 .map(|(key, value)| (key, value.into_value()))
1110 .collect(),
1111 )
1112 }
1113}
1114
1115impl OrderedJsonValue {
1116 fn into_value(self) -> serde_json::Value {
1117 match self {
1118 Self::Null => serde_json::Value::Null,
1119 Self::Bool(value) => serde_json::Value::Bool(value),
1120 Self::Number(value) => serde_json::Value::Number(value),
1121 Self::String(value) => serde_json::Value::String(value),
1122 Self::Array(values) => {
1123 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1124 }
1125 Self::Object(value) => value.into_value(),
1126 }
1127 }
1128}
1129
1130impl Serialize for OrderedJsonValue {
1131 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1132 where
1133 S: Serializer,
1134 {
1135 match self {
1136 Self::Null => serializer.serialize_unit(),
1137 Self::Bool(value) => serializer.serialize_bool(*value),
1138 Self::Number(value) => value.serialize(serializer),
1139 Self::String(value) => serializer.serialize_str(value),
1140 Self::Array(values) => values.serialize(serializer),
1141 Self::Object(value) => value.serialize(serializer),
1142 }
1143 }
1144}
1145
1146impl<'de> Deserialize<'de> for OrderedJsonValue {
1147 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1148 where
1149 D: Deserializer<'de>,
1150 {
1151 struct OrderedValueVisitor;
1152
1153 impl<'de> Visitor<'de> for OrderedValueVisitor {
1154 type Value = OrderedJsonValue;
1155
1156 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1157 formatter.write_str("a JSON value with ordered object members")
1158 }
1159
1160 fn visit_unit<E>(self) -> Result<Self::Value, E>
1161 where
1162 E: serde::de::Error,
1163 {
1164 Ok(OrderedJsonValue::Null)
1165 }
1166
1167 fn visit_none<E>(self) -> Result<Self::Value, E>
1168 where
1169 E: serde::de::Error,
1170 {
1171 Ok(OrderedJsonValue::Null)
1172 }
1173
1174 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1175 where
1176 D: Deserializer<'de>,
1177 {
1178 OrderedJsonValue::deserialize(deserializer)
1179 }
1180
1181 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1182 where
1183 E: serde::de::Error,
1184 {
1185 Ok(OrderedJsonValue::Bool(value))
1186 }
1187
1188 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1189 where
1190 E: serde::de::Error,
1191 {
1192 Ok(OrderedJsonValue::Number(value.into()))
1193 }
1194
1195 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1196 where
1197 E: serde::de::Error,
1198 {
1199 Ok(OrderedJsonValue::Number(value.into()))
1200 }
1201
1202 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1203 where
1204 E: serde::de::Error,
1205 {
1206 serde_json::Number::from_f64(value)
1207 .map(OrderedJsonValue::Number)
1208 .ok_or_else(|| E::custom("non-finite JSON number"))
1209 }
1210
1211 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1212 where
1213 E: serde::de::Error,
1214 {
1215 Ok(OrderedJsonValue::String(value.to_owned()))
1216 }
1217
1218 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1219 where
1220 E: serde::de::Error,
1221 {
1222 Ok(OrderedJsonValue::String(value))
1223 }
1224
1225 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1226 where
1227 A: SeqAccess<'de>,
1228 {
1229 let mut values = Vec::new();
1230 while let Some(value) = sequence.next_element()? {
1231 values.push(value);
1232 }
1233 Ok(OrderedJsonValue::Array(values))
1234 }
1235
1236 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1237 where
1238 A: MapAccess<'de>,
1239 {
1240 let mut entries = Vec::new();
1241 while let Some((key, value)) = map.next_entry()? {
1242 entries.push((key, value));
1243 }
1244 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1245 }
1246 }
1247
1248 deserializer.deserialize_any(OrderedValueVisitor)
1249 }
1250}
1251
1252impl Serialize for OrderedJsonObject {
1253 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1254 where
1255 S: Serializer,
1256 {
1257 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1258 for (key, value) in &self.0 {
1259 map.serialize_entry(key, value)?;
1260 }
1261 map.end()
1262 }
1263}
1264
1265impl<'de> Deserialize<'de> for OrderedJsonObject {
1266 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1267 where
1268 D: Deserializer<'de>,
1269 {
1270 struct OrderedObjectVisitor;
1271
1272 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1273 type Value = OrderedJsonObject;
1274
1275 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1276 formatter.write_str("an object with ordered JSON members")
1277 }
1278
1279 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1280 where
1281 A: MapAccess<'de>,
1282 {
1283 let mut entries = Vec::new();
1284 while let Some((key, value)) = map.next_entry()? {
1285 entries.push((key, value));
1286 }
1287 Ok(OrderedJsonObject(entries))
1288 }
1289 }
1290
1291 deserializer.deserialize_map(OrderedObjectVisitor)
1292 }
1293}
1294
1295fn read_tagged<'de, D>(
1296 deserializer: D,
1297 field: &'static str,
1298) -> Result<(String, OrderedJsonObject), D::Error>
1299where
1300 D: Deserializer<'de>,
1301{
1302 let body = OrderedJsonObject::deserialize(deserializer)?;
1303 let mut tag = None;
1304 for (key, value) in body.as_entries() {
1305 if key != field {
1306 continue;
1307 }
1308 if tag.is_some() {
1309 return Err(D::Error::custom(format!(
1310 "tagged object has duplicate `{field}` field"
1311 )));
1312 }
1313 let OrderedJsonValue::String(value) = value else {
1314 return Err(D::Error::custom(format!(
1315 "tagged object has no string `{field}` field"
1316 )));
1317 };
1318 tag = Some(value);
1319 }
1320 let Some(tag) = tag else {
1321 return Err(D::Error::custom(format!(
1322 "tagged object has no string `{field}` field"
1323 )));
1324 };
1325 Ok((tag.to_string(), body))
1326}
1327
1328fn read_ordered_tagged(
1329 value: OrderedJsonValue,
1330 field: &'static str,
1331) -> Result<(String, OrderedJsonObject), String> {
1332 let OrderedJsonValue::Object(body) = value else {
1333 return Err(format!("expected tagged object with `{field}` field"));
1334 };
1335 let mut tag = None;
1336 for (key, value) in body.as_entries() {
1337 if key != field {
1338 continue;
1339 }
1340 if tag.is_some() {
1341 return Err(format!("tagged object has duplicate `{field}` field"));
1342 }
1343 let OrderedJsonValue::String(value) = value else {
1344 return Err(format!("tagged object has no string `{field}` field"));
1345 };
1346 tag = Some(value);
1347 }
1348 let Some(tag) = tag else {
1349 return Err(format!("tagged object has no string `{field}` field"));
1350 };
1351 Ok((tag.to_string(), body))
1352}
1353
1354fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1355 body.as_entries()
1356 .iter()
1357 .find_map(|(key, value)| (key == field).then_some(value))
1358}
1359
1360fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1361 match ordered_field(body, field) {
1362 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1363 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1364 None => Err(format!("tagged object has no `{field}` field")),
1365 }
1366}
1367
1368fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1369 let (tag, body) = read_ordered_tagged(value, "method")?;
1370 match tag.as_str() {
1371 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1372 digest: ordered_string(&body, "digest")?,
1373 }),
1374 "macos_spawn_inode" => {
1375 let device = ordered_field(&body, "device")
1376 .and_then(|value| match value {
1377 OrderedJsonValue::Number(number) => number.as_u64(),
1378 _ => None,
1379 })
1380 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1381 let inode = ordered_field(&body, "inode")
1382 .and_then(|value| match value {
1383 OrderedJsonValue::Number(number) => number.as_u64(),
1384 _ => None,
1385 })
1386 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1387 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1388 }
1389 "windows_spawn_file_id" => {
1390 let wire: RunningImageEvidenceWire = serde_json::from_value(
1391 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1392 )
1393 .map_err(|error| error.to_string())?;
1394 match wire {
1395 RunningImageEvidenceWire::WindowsSpawnFileId {
1396 volume_serial_number,
1397 file_id,
1398 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1399 volume_serial_number,
1400 file_id,
1401 }),
1402 _ => unreachable!(),
1403 }
1404 }
1405 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1406 }
1407}
1408
1409impl Serialize for ModuleDeclaredProvenance {
1410 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1411 where
1412 S: Serializer,
1413 {
1414 match self {
1415 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1416 build: build.clone(),
1417 }
1418 .serialize(serializer),
1419 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1420 Self::Unknown { body, .. } => body.serialize(serializer),
1421 }
1422 }
1423}
1424
1425impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1426 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1427 where
1428 D: serde::Deserializer<'de>,
1429 {
1430 let (tag, value) = read_tagged(deserializer, "status")?;
1431 match tag.as_str() {
1432 "reported" => match serde_json::from_value(value.into_value())
1433 .map_err(D::Error::custom)?
1434 {
1435 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1436 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1437 },
1438 "unverifiable" => {
1439 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1440 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1441 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1442 }
1443 }
1444 _ => Ok(Self::Unknown { tag, body: value }),
1445 }
1446 }
1447}
1448
1449impl Serialize for RunningImageAgreement {
1450 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1451 where
1452 S: Serializer,
1453 {
1454 match self {
1455 Self::Match { evidence } => RunningImageAgreementWire::Match {
1456 evidence: evidence.clone(),
1457 }
1458 .serialize(serializer),
1459 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1460 running: running.clone(),
1461 disk: disk.clone(),
1462 }
1463 .serialize(serializer),
1464 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1465 reason: reason.clone(),
1466 }
1467 .serialize(serializer),
1468 Self::Unknown { body, .. } => body.serialize(serializer),
1469 }
1470 }
1471}
1472
1473impl Serialize for ReloadPathAgreement {
1474 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1475 where
1476 S: Serializer,
1477 {
1478 match self {
1479 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1480 Self::Mismatch {
1481 configured,
1482 spawned_from,
1483 } => ReloadPathAgreementWire::Mismatch {
1484 configured: configured.clone(),
1485 spawned_from: spawned_from.clone(),
1486 }
1487 .serialize(serializer),
1488 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1489 reason: reason.clone(),
1490 }
1491 .serialize(serializer),
1492 Self::Unknown { body, .. } => body.serialize(serializer),
1493 }
1494 }
1495}
1496
1497impl Serialize for LaunchSpecAgreement {
1498 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1499 where
1500 S: Serializer,
1501 {
1502 match self {
1503 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1504 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1505 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1506 reason: reason.clone(),
1507 }
1508 .serialize(serializer),
1509 Self::Unknown { body, .. } => body.serialize(serializer),
1510 }
1511 }
1512}
1513
1514impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1515 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1516 where
1517 D: Deserializer<'de>,
1518 {
1519 let (tag, body) = read_tagged(deserializer, "status")?;
1520 match tag.as_str() {
1521 "match" => Ok(Self::Match),
1522 "mismatch" => Ok(Self::Mismatch),
1523 "unavailable" => match serde_json::from_value(body.into_value())
1524 .map_err(D::Error::custom)?
1525 {
1526 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1527 _ => unreachable!(),
1528 },
1529 _ => Ok(Self::Unknown { tag, body }),
1530 }
1531 }
1532}
1533
1534impl<'de> Deserialize<'de> for ReloadPathAgreement {
1535 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1536 where
1537 D: Deserializer<'de>,
1538 {
1539 let (tag, body) = read_tagged(deserializer, "status")?;
1540 match tag.as_str() {
1541 "match" => Ok(Self::Match),
1542 "mismatch" => {
1543 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1544 ReloadPathAgreementWire::Mismatch {
1545 configured,
1546 spawned_from,
1547 } => Ok(Self::Mismatch {
1548 configured,
1549 spawned_from,
1550 }),
1551 _ => unreachable!(),
1552 }
1553 }
1554 "unavailable" => match serde_json::from_value(body.into_value())
1555 .map_err(D::Error::custom)?
1556 {
1557 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1558 _ => unreachable!(),
1559 },
1560 _ => Ok(Self::Unknown { tag, body }),
1561 }
1562 }
1563}
1564
1565impl<'de> Deserialize<'de> for RunningImageAgreement {
1566 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1567 where
1568 D: serde::Deserializer<'de>,
1569 {
1570 let (tag, value) = read_tagged(deserializer, "status")?;
1571 match tag.as_str() {
1572 "match" => Ok(Self::Match {
1573 evidence: decode_running_image_evidence(
1574 ordered_field(&value, "evidence")
1575 .cloned()
1576 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1577 )
1578 .map_err(D::Error::custom)?,
1579 }),
1580 "mismatch" => Ok(Self::Mismatch {
1581 running: decode_running_image_evidence(
1582 ordered_field(&value, "running")
1583 .cloned()
1584 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1585 )
1586 .map_err(D::Error::custom)?,
1587 disk: decode_running_image_evidence(
1588 ordered_field(&value, "disk")
1589 .cloned()
1590 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1591 )
1592 .map_err(D::Error::custom)?,
1593 }),
1594 "unavailable" => Ok(Self::Unavailable {
1595 reason: serde_json::from_value(
1596 ordered_field(&value, "reason")
1597 .cloned()
1598 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1599 .into_value(),
1600 )
1601 .map_err(D::Error::custom)?,
1602 }),
1603 _ => Ok(Self::Unknown { tag, body: value }),
1604 }
1605 }
1606}
1607
1608impl Serialize for ChildResourceUsage {
1609 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1610 where
1611 S: Serializer,
1612 {
1613 match self {
1614 Self::Measured(reading) => {
1615 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1616 }
1617 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1618 reason: reason.clone(),
1619 }
1620 .serialize(serializer),
1621 Self::Unknown { body, .. } => body.serialize(serializer),
1622 }
1623 }
1624}
1625
1626impl<'de> Deserialize<'de> for ChildResourceUsage {
1627 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1628 where
1629 D: Deserializer<'de>,
1630 {
1631 let (tag, body) = read_tagged(deserializer, "status")?;
1632 match tag.as_str() {
1633 "measured" | "unavailable" => {
1634 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1635 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1636 ChildResourceUsageWire::Unavailable { reason } => {
1637 Ok(Self::Unavailable { reason })
1638 }
1639 }
1640 }
1641 _ => Ok(Self::Unknown { tag, body }),
1642 }
1643 }
1644}
1645
1646impl Serialize for RunningImageEvidence {
1647 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1648 where
1649 S: Serializer,
1650 {
1651 match self {
1652 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1653 digest: digest.clone(),
1654 }
1655 .serialize(serializer),
1656 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1657 device: *device,
1658 inode: *inode,
1659 }
1660 .serialize(serializer),
1661 Self::WindowsSpawnFileId {
1662 volume_serial_number,
1663 file_id,
1664 } => RunningImageEvidenceWire::WindowsSpawnFileId {
1665 volume_serial_number: *volume_serial_number,
1666 file_id: *file_id,
1667 }
1668 .serialize(serializer),
1669 Self::Unknown { body, .. } => body.serialize(serializer),
1670 }
1671 }
1672}
1673
1674impl<'de> Deserialize<'de> for RunningImageEvidence {
1675 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1676 where
1677 D: serde::Deserializer<'de>,
1678 {
1679 let (tag, value) = read_tagged(deserializer, "method")?;
1680 match tag.as_str() {
1681 "linux_proc_sha256" => {
1682 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1683 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1684 Ok(Self::LinuxProcSha256 { digest })
1685 }
1686 _ => unreachable!(),
1687 }
1688 }
1689 "macos_spawn_inode" => {
1690 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1691 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1692 Ok(Self::MacosSpawnInode { device, inode })
1693 }
1694 _ => unreachable!(),
1695 }
1696 }
1697 "windows_spawn_file_id" => {
1698 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1699 RunningImageEvidenceWire::WindowsSpawnFileId {
1700 volume_serial_number,
1701 file_id,
1702 } => Ok(Self::WindowsSpawnFileId {
1703 volume_serial_number,
1704 file_id,
1705 }),
1706 _ => unreachable!(),
1707 }
1708 }
1709 _ => Ok(Self::Unknown { tag, body: value }),
1710 }
1711 }
1712}
1713
1714impl Serialize for SupervisorRouteConsumer {
1715 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1716 where
1717 S: Serializer,
1718 {
1719 match self {
1720 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1721 module_id: module_id.clone(),
1722 }
1723 .serialize(serializer),
1724 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1725 connection_id: *connection_id,
1726 }
1727 .serialize(serializer),
1728 Self::Unknown { body, .. } => body.serialize(serializer),
1729 }
1730 }
1731}
1732
1733impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1734 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1735 where
1736 D: serde::Deserializer<'de>,
1737 {
1738 let (tag, value) = read_tagged(deserializer, "kind")?;
1739 match tag.as_str() {
1740 "reserved" => {
1741 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1742 SupervisorRouteConsumerWire::Reserved { module_id } => {
1743 Ok(Self::Reserved { module_id })
1744 }
1745 _ => unreachable!(),
1746 }
1747 }
1748 "direct" => {
1749 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1750 SupervisorRouteConsumerWire::Direct { connection_id } => {
1751 Ok(Self::Direct { connection_id })
1752 }
1753 _ => unreachable!(),
1754 }
1755 }
1756 _ => Ok(Self::Unknown { tag, body: value }),
1757 }
1758 }
1759}
1760
1761impl Serialize for StderrCaptureState {
1762 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1763 where
1764 S: Serializer,
1765 {
1766 match self {
1767 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1768 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1769 reason: reason.clone(),
1770 }
1771 .serialize(serializer),
1772 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1773 reason: reason.clone(),
1774 }
1775 .serialize(serializer),
1776 Self::Unknown { body, .. } => body.serialize(serializer),
1777 }
1778 }
1779}
1780
1781impl<'de> Deserialize<'de> for StderrCaptureState {
1782 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1783 where
1784 D: serde::Deserializer<'de>,
1785 {
1786 let (tag, value) = read_tagged(deserializer, "state")?;
1787 match tag.as_str() {
1788 "captured" => {
1789 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1790 StderrCaptureStateWire::Captured => Ok(Self::Captured),
1791 _ => unreachable!(),
1792 }
1793 }
1794 "incomplete" => match serde_json::from_value(value.into_value())
1795 .map_err(D::Error::custom)?
1796 {
1797 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1798 _ => unreachable!(),
1799 },
1800 "not_captured" => match serde_json::from_value(value.into_value())
1801 .map_err(D::Error::custom)?
1802 {
1803 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1804 _ => unreachable!(),
1805 },
1806 _ => Ok(Self::Unknown { tag, body: value }),
1807 }
1808 }
1809}
1810
1811impl Serialize for StderrTailEntry {
1812 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1813 where
1814 S: Serializer,
1815 {
1816 match self {
1817 Self::Line {
1818 text,
1819 truncated,
1820 at_ms,
1821 } => StderrTailEntryWire::Line {
1822 text: text.clone(),
1823 truncated: *truncated,
1824 at_ms: *at_ms,
1825 }
1826 .serialize(serializer),
1827 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1828 Self::Unknown { body, .. } => body.serialize(serializer),
1829 }
1830 }
1831}
1832
1833impl<'de> Deserialize<'de> for StderrTailEntry {
1834 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1835 where
1836 D: serde::Deserializer<'de>,
1837 {
1838 let (tag, value) = read_tagged(deserializer, "kind")?;
1839 match tag.as_str() {
1840 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1841 StderrTailEntryWire::Line {
1842 text,
1843 truncated,
1844 at_ms,
1845 } => Ok(Self::Line {
1846 text,
1847 truncated,
1848 at_ms,
1849 }),
1850 _ => unreachable!(),
1851 },
1852 "process_start" => {
1853 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1854 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1855 _ => unreachable!(),
1856 }
1857 }
1858 _ => Ok(Self::Unknown { tag, body: value }),
1859 }
1860 }
1861}
1862
1863fn is_zero_u64(value: &u64) -> bool {
1864 *value == 0
1865}
1866
1867fn default_true() -> bool {
1868 true
1869}
1870
1871#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1873pub struct TerminalHistory {
1874 pub daemon_started_at_ms: u64,
1876 pub entries: Vec<TerminalEntry>,
1877 #[serde(default, skip_serializing_if = "is_zero_u64")]
1880 pub dropped: u64,
1881 #[serde(default, skip_serializing_if = "is_zero_u64")]
1884 pub journal_skipped_lines: u64,
1885 #[serde(default, skip_serializing_if = "is_zero_u64")]
1887 pub journal_read_errors: u64,
1888 #[serde(default, skip_serializing_if = "is_zero_u64")]
1890 pub journal_write_failures: u64,
1891}
1892
1893#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1895pub struct TerminalEntry {
1896 #[serde(default, skip_serializing_if = "Option::is_none")]
1899 pub daemon_incarnation: Option<String>,
1900 #[serde(default, skip_serializing_if = "Option::is_none")]
1901 pub exit_code: Option<i32>,
1902 #[serde(default, skip_serializing_if = "Option::is_none")]
1903 pub exit_signal: Option<i32>,
1904 pub at_ms: u64,
1905 pub disposition: TerminalDisposition,
1906 #[serde(default, skip_serializing_if = "Option::is_none")]
1910 pub exit_kind: Option<TerminalExitKind>,
1911 #[serde(default, skip_serializing_if = "Option::is_none")]
1918 pub disposition_detail: Option<String>,
1919}
1920
1921#[derive(Debug, Clone, PartialEq, Eq)]
1926pub enum TerminalExitKind {
1927 Clean,
1928 Crash,
1929 DeliberateSeverance,
1930 Unknown(String),
1931}
1932
1933impl TerminalExitKind {
1934 fn wire_name(&self) -> &str {
1935 match self {
1936 Self::Clean => "clean",
1937 Self::Crash => "crash",
1938 Self::DeliberateSeverance => "deliberate_severance",
1939 Self::Unknown(value) => value,
1940 }
1941 }
1942}
1943
1944impl Serialize for TerminalExitKind {
1945 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1946 where
1947 S: serde::Serializer,
1948 {
1949 serializer.serialize_str(self.wire_name())
1950 }
1951}
1952
1953impl<'de> Deserialize<'de> for TerminalExitKind {
1954 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1955 where
1956 D: serde::Deserializer<'de>,
1957 {
1958 let value = String::deserialize(deserializer)?;
1959 Ok(match value.as_str() {
1960 "clean" => Self::Clean,
1961 "crash" => Self::Crash,
1962 "deliberate_severance" => Self::DeliberateSeverance,
1963 _ => Self::Unknown(value),
1964 })
1965 }
1966}
1967
1968open_string_enum! {
1969 TerminalDisposition {
1971 Stopped => "stopped",
1972 Disabled => "disabled",
1973 Failed => "failed",
1974 Restarting => "restarting",
1975 DaemonShutdown => "daemon_shutdown",
1980 }
1981}
1982
1983#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1984#[serde(rename_all = "snake_case")]
1985pub enum PollKind {
1986 Status,
1987 Liveness,
1988}
1989
1990#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2002#[non_exhaustive]
2003pub struct CatalogEntry {
2004 pub module_id: String,
2005 #[serde(default = "default_true")]
2016 pub ready: bool,
2017 #[serde(default, skip_serializing_if = "Option::is_none")]
2021 pub not_ready: Option<NotReadyReason>,
2022 #[serde(default, skip_serializing_if = "Option::is_none")]
2043 pub module_version: Option<String>,
2044 #[serde(default, skip_serializing_if = "Option::is_none")]
2047 pub provenance: Option<ManifestProvenance>,
2048 pub roles: Vec<ProviderRole>,
2049 pub control_ops: Vec<String>,
2050 #[serde(default, skip_serializing_if = "Option::is_none")]
2055 pub capabilities: Option<CapabilityDeclarations>,
2056 #[serde(default, skip_serializing_if = "Option::is_none")]
2059 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2060 #[serde(default, skip_serializing_if = "Option::is_none")]
2064 pub events: Option<Vec<EventDeclaration>>,
2065 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2068 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2069 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2072 pub operation_payload: BTreeMap<String, OperationPayload>,
2073 #[serde(default, skip_serializing_if = "Option::is_none")]
2079 pub flow_operations: Option<Vec<String>>,
2080 #[serde(default, skip_serializing_if = "Option::is_none")]
2086 pub confirm_operations: Option<Vec<String>>,
2087 #[serde(default, skip_serializing_if = "Option::is_none")]
2090 pub rich_ui: Option<RichUiDescriptor>,
2091 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2094 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2095 #[serde(default, skip_serializing_if = "is_false")]
2098 pub nonce_verified: bool,
2099}
2100
2101impl CatalogEntry {
2102 #[must_use]
2104 pub fn new(
2105 module_id: impl Into<String>,
2106 roles: Vec<ProviderRole>,
2107 control_ops: Vec<String>,
2108 ) -> Self {
2109 Self {
2110 module_id: module_id.into(),
2111 ready: default_true(),
2112 not_ready: None,
2113 module_version: None,
2114 provenance: None,
2115 roles,
2116 control_ops,
2117 capabilities: None,
2118 self_signals: None,
2119 events: None,
2120 operation_delivery: BTreeMap::new(),
2121 operation_payload: BTreeMap::new(),
2122 flow_operations: None,
2123 confirm_operations: None,
2124 rich_ui: None,
2125 role_declarations: BTreeMap::new(),
2126 nonce_verified: false,
2127 }
2128 }
2129
2130 #[must_use]
2132 pub fn with_operation_payload(
2133 mut self,
2134 operation_payload: BTreeMap<String, OperationPayload>,
2135 ) -> Self {
2136 self.operation_payload = operation_payload;
2137 self
2138 }
2139
2140 #[must_use]
2143 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2144 self.flow_operations = flow_operations;
2145 self
2146 }
2147
2148 #[must_use]
2151 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2152 self.confirm_operations = confirm_operations;
2153 self
2154 }
2155
2156 #[must_use]
2158 pub fn with_ready(mut self, ready: bool) -> Self {
2159 self.ready = ready;
2160 self
2161 }
2162
2163 #[must_use]
2165 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2166 self.not_ready = not_ready;
2167 self
2168 }
2169
2170 #[must_use]
2172 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2173 self.module_version = module_version;
2174 self
2175 }
2176
2177 #[must_use]
2179 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2180 self.provenance = provenance;
2181 self
2182 }
2183
2184 #[must_use]
2186 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2187 self.capabilities = capabilities;
2188 self
2189 }
2190
2191 #[must_use]
2193 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2194 self.self_signals = self_signals;
2195 self
2196 }
2197
2198 #[must_use]
2200 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2201 self.events = events;
2202 self
2203 }
2204
2205 #[must_use]
2208 pub fn with_operation_delivery(
2209 mut self,
2210 operation_delivery: BTreeMap<String, OperationDelivery>,
2211 ) -> Self {
2212 self.operation_delivery = operation_delivery;
2213 self
2214 }
2215
2216 #[must_use]
2218 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2219 self.rich_ui = rich_ui;
2220 self
2221 }
2222
2223 #[must_use]
2225 pub fn with_role_declarations(
2226 mut self,
2227 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2228 ) -> Self {
2229 self.role_declarations = role_declarations;
2230 self
2231 }
2232
2233 #[must_use]
2236 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2237 self.nonce_verified = nonce_verified;
2238 self
2239 }
2240}
2241
2242fn is_false(value: &bool) -> bool {
2243 !value
2244}
2245
2246#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2248pub struct NotReadyReason {
2249 pub reason: String,
2254 #[serde(default, skip_serializing_if = "Option::is_none")]
2257 pub capability: Option<String>,
2258}
2259
2260impl NotReadyReason {
2261 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2262 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2263}
2264
2265#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2266pub struct CapabilityRequirementStatus {
2267 pub consumer: String,
2268 pub capability: String,
2269 pub need: String,
2270 pub verdict: String,
2271 pub episode_seq: u64,
2272 pub config_satisfiable: bool,
2273 pub runtime_available: bool,
2274 pub detail: String,
2275}
2276
2277#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2278pub struct SupervisorRescanResult {
2279 pub added: Vec<String>,
2280 pub removed: Vec<String>,
2281 pub changed_pending_reload: Vec<String>,
2282 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2295 pub enabled_changes: Vec<String>,
2296 pub unchanged: u32,
2297 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2305 pub preview: bool,
2306 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2324 pub restart_required: Vec<String>,
2325 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2329 pub capability_warnings: Vec<String>,
2330 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2337 pub module_actions: Vec<RescanModuleAction>,
2338 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2342 pub earlier_pending: Vec<String>,
2343 #[serde(default, skip_serializing_if = "Option::is_none")]
2346 pub expect: Option<RescanExpect>,
2347}
2348
2349#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2365#[serde(rename_all = "snake_case")]
2366pub enum ModuleProtocol {
2367 #[default]
2371 Subc,
2372 None,
2381}
2382
2383#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2395#[non_exhaustive]
2396pub struct SupervisorEntry {
2397 #[serde(default, skip_serializing_if = "Option::is_none")]
2400 pub waiting_for_previous_pid: Option<u32>,
2401 pub module_id: String,
2402 pub state: String,
2403 #[serde(default, skip_serializing_if = "Option::is_none")]
2407 pub next_retry_at_ms: Option<u64>,
2408 pub enabled: bool,
2409 #[serde(default, skip_serializing_if = "Option::is_none")]
2412 pub configured_enabled: Option<bool>,
2413 pub live: bool,
2423 #[serde(default)]
2427 pub protocol: ModuleProtocol,
2428 #[serde(default, skip_serializing_if = "Option::is_none")]
2431 pub launch_nonce_env: Option<bool>,
2432 #[serde(default, skip_serializing_if = "Option::is_none")]
2438 pub launch_nonce_source: Option<String>,
2439 pub health: SupervisorHealthStatus,
2440 #[serde(default, skip_serializing_if = "Option::is_none")]
2443 pub pending_reload: Option<PendingReloadVerdict>,
2444 #[serde(default)]
2450 pub last_probe_ms: Option<u64>,
2451 #[serde(default, skip_serializing_if = "Option::is_none")]
2455 pub last_exit_code: Option<i32>,
2456 #[serde(default, skip_serializing_if = "Option::is_none")]
2460 pub last_exit_signal: Option<i32>,
2461 #[serde(default, skip_serializing_if = "Option::is_none")]
2465 pub last_exit_ms: Option<u64>,
2466 #[serde(default, skip_serializing_if = "Option::is_none")]
2469 pub last_exit_kind: Option<TerminalExitKind>,
2470 #[serde(default, skip_serializing_if = "Option::is_none")]
2487 pub restart_count: Option<u32>,
2488 #[serde(default, skip_serializing_if = "Option::is_none")]
2491 pub max_restarts: Option<u32>,
2492 #[serde(default, skip_serializing_if = "Option::is_none")]
2495 pub lifetime_restarts: Option<u32>,
2496 #[serde(default, skip_serializing_if = "Option::is_none")]
2500 pub spawn_generation: Option<u64>,
2501 #[serde(default, skip_serializing_if = "Option::is_none")]
2511 pub restart_window_secs: Option<u64>,
2512 #[serde(default, skip_serializing_if = "Option::is_none")]
2516 pub drain_timeout_ms: Option<u64>,
2517 #[serde(default, skip_serializing_if = "Option::is_none")]
2520 pub restart_backoff_ms: Option<u64>,
2521 #[serde(default, skip_serializing_if = "Option::is_none")]
2524 pub restart_max_backoff_ms: Option<u64>,
2525 #[serde(default, skip_serializing_if = "Option::is_none")]
2538 pub resources: Option<ChildResourceUsage>,
2539 #[serde(default, skip_serializing_if = "Option::is_none")]
2542 pub subtree: Option<SubtreeReading>,
2543}
2544
2545impl SupervisorEntry {
2546 #[must_use]
2548 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2549 self.next_retry_at_ms = next_retry_at_ms;
2550 self
2551 }
2552
2553 #[must_use]
2555 pub fn new(
2556 module_id: impl Into<String>,
2557 state: impl Into<String>,
2558 enabled: bool,
2559 live: bool,
2560 health: SupervisorHealthStatus,
2561 ) -> Self {
2562 Self {
2563 module_id: module_id.into(),
2564 state: state.into(),
2565 next_retry_at_ms: None,
2566 waiting_for_previous_pid: None,
2567 enabled,
2568 configured_enabled: None,
2569 live,
2570 protocol: ModuleProtocol::default(),
2571 launch_nonce_env: None,
2572 launch_nonce_source: None,
2573 health,
2574 pending_reload: None,
2575 last_probe_ms: None,
2576 last_exit_code: None,
2577 last_exit_signal: None,
2578 last_exit_ms: None,
2579 last_exit_kind: None,
2580 restart_count: None,
2581 max_restarts: None,
2582 lifetime_restarts: None,
2583 spawn_generation: None,
2584 restart_window_secs: None,
2585 drain_timeout_ms: None,
2586 restart_backoff_ms: None,
2587 restart_max_backoff_ms: None,
2588 resources: None,
2589 subtree: None,
2590 }
2591 }
2592
2593 #[must_use]
2595 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2596 self.protocol = protocol;
2597 self
2598 }
2599
2600 #[must_use]
2602 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2603 self.configured_enabled = configured_enabled;
2604 self
2605 }
2606
2607 #[must_use]
2609 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2610 self.launch_nonce_env = launch_nonce_env;
2611 self
2612 }
2613
2614 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2615 self.launch_nonce_source = source;
2616 self
2617 }
2618
2619 #[must_use]
2620 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2621 self.waiting_for_previous_pid = pid;
2622 self
2623 }
2624
2625 #[must_use]
2627 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2628 self.pending_reload = pending_reload;
2629 self
2630 }
2631
2632 #[must_use]
2634 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2635 self.last_probe_ms = last_probe_ms;
2636 self
2637 }
2638
2639 #[must_use]
2641 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2642 self.last_exit_code = last_exit_code;
2643 self
2644 }
2645
2646 #[must_use]
2648 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2649 self.last_exit_signal = last_exit_signal;
2650 self
2651 }
2652
2653 #[must_use]
2655 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2656 self.last_exit_ms = last_exit_ms;
2657 self
2658 }
2659
2660 #[must_use]
2662 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2663 self.last_exit_kind = last_exit_kind;
2664 self
2665 }
2666
2667 #[must_use]
2669 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2670 self.restart_count = restart_count;
2671 self
2672 }
2673
2674 #[must_use]
2676 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2677 self.max_restarts = max_restarts;
2678 self
2679 }
2680
2681 #[must_use]
2683 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2684 self.lifetime_restarts = lifetime_restarts;
2685 self
2686 }
2687
2688 #[must_use]
2690 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2691 self.spawn_generation = spawn_generation;
2692 self
2693 }
2694
2695 #[must_use]
2697 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2698 self.restart_window_secs = restart_window_secs;
2699 self
2700 }
2701
2702 #[must_use]
2704 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2705 self.drain_timeout_ms = drain_timeout_ms;
2706 self
2707 }
2708
2709 #[must_use]
2711 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2712 self.restart_backoff_ms = restart_backoff_ms;
2713 self
2714 }
2715
2716 #[must_use]
2718 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2719 self.restart_max_backoff_ms = restart_max_backoff_ms;
2720 self
2721 }
2722
2723 #[must_use]
2725 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2726 self.resources = resources;
2727 self
2728 }
2729
2730 #[must_use]
2732 pub fn with_subtree(mut self, subtree: Option<SubtreeReading>) -> Self {
2733 self.subtree = subtree;
2734 self
2735 }
2736}
2737
2738#[derive(Debug, Clone, PartialEq)]
2741pub enum ChildResourceUsage {
2742 Measured(ChildResourceReading),
2743 Unavailable {
2744 reason: ChildResourceUnavailableReason,
2745 },
2746 Unknown {
2749 tag: String,
2750 body: OrderedJsonObject,
2751 },
2752}
2753
2754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2756pub struct ChildResourceReading {
2757 pub memory_bytes: u64,
2760 pub memory_kind: ChildMemoryKind,
2761 #[serde(default, skip_serializing_if = "Option::is_none")]
2764 pub swap_bytes: Option<u64>,
2765 pub cpu_user_ms: u64,
2769 pub cpu_system_ms: u64,
2772}
2773
2774open_string_enum! {
2775 ChildMemoryKind {
2777 PhysFootprint => "phys_footprint",
2781 ResidentSet => "resident_set",
2784 WindowsWorkingSet => "windows_working_set",
2787 }
2788}
2789
2790open_string_enum! {
2791 ChildResourceUnavailableReason {
2793 NotRunning => "not_running",
2795 UnsupportedPlatform => "unsupported_platform",
2797 Unreadable => "unreadable",
2800 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2803 }
2804}
2805
2806#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2807#[serde(rename_all = "snake_case")]
2808pub enum SupervisorHealthStatus {
2809 Ok,
2810 Degraded,
2811 Failing,
2812 Unresponsive,
2813 Unknown,
2814}
2815
2816#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2817pub struct SupervisorHealthEntry {
2818 pub module_id: String,
2819 pub status: SupervisorHealthStatus,
2820 #[serde(default, skip_serializing_if = "Option::is_none")]
2826 pub detail: Option<String>,
2827 #[serde(default, skip_serializing_if = "Option::is_none")]
2832 pub metrics: Option<serde_json::Value>,
2833 pub consecutive_failures: u32,
2834 #[serde(default)]
2837 pub late_answer_count: u64,
2838 #[serde(default, skip_serializing_if = "Option::is_none")]
2840 pub last_late_answer_latency_ms: Option<u64>,
2841 #[serde(default)]
2846 pub last_action: Option<String>,
2847 #[serde(default)]
2850 pub last_action_ms: Option<u64>,
2851 #[serde(default, skip_serializing_if = "Option::is_none")]
2864 pub last_probe_ms: Option<u64>,
2865}
2866
2867#[cfg(test)]
2868mod tests {
2869 #[test]
2870 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2871 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2872 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2873 assert_eq!(decoded.configured_enabled, None);
2874 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2875 }
2876
2877 #[test]
2878 fn configured_enabled_values_round_trip_in_list() {
2879 for enabled in [false, true] {
2880 let entry = SupervisorEntry::new(
2881 "provider",
2882 "running",
2883 true,
2884 true,
2885 SupervisorHealthStatus::Unknown,
2886 )
2887 .with_configured_enabled(Some(enabled));
2888 let entry_json = serde_json::to_value(&entry).unwrap();
2889 assert_eq!(entry_json["configured_enabled"], enabled);
2890 assert_eq!(
2891 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
2892 entry
2893 );
2894 }
2895 }
2896
2897 #[test]
2898 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2899 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2900 volume_serial_number: u64::MAX,
2901 file_id: [
2902 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2903 ],
2904 };
2905 let agreement = super::RunningImageAgreement::Match { evidence };
2906 let encoded = serde_json::to_string(&agreement).unwrap();
2907 assert!(encoded.contains("windows_spawn_file_id"));
2908 assert_eq!(
2909 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
2910 agreement
2911 );
2912 }
2913
2914 #[test]
2915 fn unix_running_image_evidence_keeps_original_wire_bytes() {
2916 assert_eq!(
2917 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
2918 device: 7,
2919 inode: 11
2920 })
2921 .unwrap(),
2922 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
2923 );
2924 assert_eq!(
2925 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
2926 digest: "abc".to_owned()
2927 })
2928 .unwrap(),
2929 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
2930 );
2931 }
2932 use super::*;
2933 use subc_protocol::{BindIdentity, RouteTarget};
2934
2935 #[test]
2936 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2937 let entry = TerminalEntry {
2938 daemon_incarnation: Some("daemon-before-restart".into()),
2939 exit_code: Some(1),
2940 exit_signal: None,
2941 at_ms: 1_700_000_000_123,
2942 disposition: TerminalDisposition::Restarting,
2943 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2944 disposition_detail: None,
2945 };
2946 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2947 assert_eq!(
2948 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2949 ["exit_kind"],
2950 "deliberate_severance"
2951 );
2952
2953 #[derive(serde::Deserialize)]
2954 struct LegacyTerminalEntry {
2955 exit_code: Option<i32>,
2956 exit_signal: Option<i32>,
2957 at_ms: u64,
2958 disposition: TerminalDisposition,
2959 }
2960
2961 let decoded: LegacyTerminalEntry =
2962 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2963 assert_eq!(decoded.exit_code, Some(1));
2964 assert_eq!(decoded.exit_signal, None);
2965 assert_eq!(decoded.at_ms, 1_700_000_000_123);
2966 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
2967
2968 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
2969 let future: TerminalEntry =
2970 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
2971 assert_eq!(
2972 future.exit_kind,
2973 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
2974 );
2975 }
2976
2977 #[test]
2978 fn terminal_incarnation_is_optional_for_older_daemons() {
2979 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
2980 "at_ms": 123,
2981 "disposition": "stopped"
2982 }))
2983 .unwrap();
2984 let encoded = serde_json::to_value(&entry).unwrap();
2985 assert_eq!(
2986 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
2987 (None, None)
2988 );
2989 }
2990
2991 #[test]
2992 fn route_poll_uses_kind_field() {
2993 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
2994 route_channel: 7,
2995 route_epoch: 11,
2996 kind: PollKind::Status,
2997 })
2998 .unwrap();
2999
3000 assert_eq!(body["op"], "route.poll");
3001 assert_eq!(body["route_epoch"], 11);
3002 assert_eq!(body["kind"], "status");
3003 assert!(body.get("op").is_some());
3004 }
3005
3006 #[test]
3007 fn route_open_is_internally_tagged() {
3008 let request = ClientControlRequest::RouteOpen {
3009 busy_refusals: None,
3010 target: RouteTarget::ToolProvider {
3011 module_id: "aft".to_string(),
3012 },
3013 identity: BindIdentity::new("opencode", "session-1"),
3014 consumer_identity: None,
3015 consumer_capabilities: None,
3016 role_versions: None,
3017 admission_facts: None,
3018 scope: None,
3019 };
3020
3021 let body = serde_json::to_value(request).unwrap();
3022 assert_eq!(body["op"], "route.open");
3023 assert_eq!(body["target"]["kind"], "tool_provider");
3024 assert!(body.get("consumer_identity").is_none());
3025 assert!(body.get("consumer_capabilities").is_none());
3026 assert!(body.get("role_versions").is_none());
3027 }
3028
3029 #[test]
3030 fn route_open_without_optional_fields_still_decodes() {
3031 let body = serde_json::json!({
3032 "op": "route.open",
3033 "target": { "kind": "tool_provider", "module_id": "aft" },
3034 "identity": {
3035 "project_root": "/tmp/project",
3036 "harness": "opencode",
3037 "session": "session-1"
3038 }
3039 });
3040
3041 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3042 let ClientControlRequest::RouteOpen {
3043 consumer_identity,
3044 consumer_capabilities,
3045 role_versions,
3046 admission_facts,
3047 ..
3048 } = decoded
3049 else {
3050 panic!("decoded wrong request variant");
3051 };
3052 assert_eq!(consumer_identity, None);
3053 assert_eq!(consumer_capabilities, None);
3054 assert_eq!(role_versions, None);
3055 assert_eq!(admission_facts, None);
3056 }
3057
3058 #[test]
3059 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3060 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3061 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3062 match decoded {
3063 ClientControlPush::RouteClosed {
3064 excluded_subscriptions,
3065 terminal,
3066 ..
3067 } => {
3068 assert_eq!(excluded_subscriptions, 0);
3069 assert_eq!(terminal, None);
3070 }
3071 other => panic!("unexpected push: {other:?}"),
3072 }
3073 assert!(!serde_json::to_string(&decoded)
3074 .unwrap()
3075 .contains("terminal"));
3076 }
3077
3078 #[test]
3079 fn old_route_closed_decoder_ignores_new_terminal_field() {
3080 #[derive(serde::Deserialize)]
3081 #[serde(tag = "op")]
3082 enum LegacyClientControlPush {
3083 #[serde(rename = "route.closed")]
3084 RouteClosed {
3085 module_id: String,
3086 reason: RouteCloseReason,
3087 drained: bool,
3088 abandoned: u32,
3089 },
3090 }
3091
3092 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3093 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3094 match decoded {
3095 LegacyClientControlPush::RouteClosed {
3096 module_id,
3097 reason,
3098 drained,
3099 abandoned,
3100 } => {
3101 assert_eq!(module_id, "aft-tools");
3102 assert_eq!(reason, RouteCloseReason::Crash);
3103 assert!(!drained);
3104 assert_eq!(abandoned, 0);
3105 }
3106 }
3107 }
3108
3109 #[test]
3110 fn supervisor_routes_is_a_control_plane_request() {
3111 let body = serde_json::json!({
3112 "op": "supervisor.routes",
3113 "module_id": "aft"
3114 });
3115
3116 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3117 assert_eq!(serde_json::to_value(request).unwrap(), body);
3118 }
3119
3120 #[test]
3121 fn diagnostic_string_enums_retain_unknown_wire_values() {
3122 let reason: RunningImageUnavailableReason =
3123 serde_json::from_str("\"future_reason\"").unwrap();
3124 let disposition: TerminalDisposition =
3125 serde_json::from_str("\"future_disposition\"").unwrap();
3126
3127 assert_eq!(
3128 reason,
3129 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3130 );
3131 assert_eq!(
3132 disposition,
3133 TerminalDisposition::Unknown("future_disposition".to_string())
3134 );
3135 }
3136
3137 #[test]
3138 fn diagnostic_string_enums_preserve_existing_wire_names() {
3139 let names = [
3140 (RunningImageUnavailableReason::NotRunning, "not_running"),
3141 (
3142 RunningImageUnavailableReason::UnsupportedPlatform,
3143 "unsupported_platform",
3144 ),
3145 (
3146 RunningImageUnavailableReason::RunningExecutableUnreadable,
3147 "running_executable_unreadable",
3148 ),
3149 (
3150 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3151 "running_executable_permission_denied",
3152 ),
3153 (
3154 RunningImageUnavailableReason::ProcessHidden,
3155 "process_hidden",
3156 ),
3157 (
3158 RunningImageUnavailableReason::SpawnedPathUnreadable,
3159 "spawned_path_unreadable",
3160 ),
3161 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3162 (
3163 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3164 "process_identity_unconfirmed",
3165 ),
3166 ];
3167 for (value, expected) in names {
3168 let wire = serde_json::to_string(&value).unwrap();
3169 assert_eq!(wire, format!("\"{expected}\""));
3170 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3171 assert_eq!(decoded, value);
3172 }
3173
3174 for (value, expected) in [
3175 (TerminalDisposition::Stopped, "stopped"),
3176 (TerminalDisposition::Disabled, "disabled"),
3177 (TerminalDisposition::Failed, "failed"),
3178 (TerminalDisposition::Restarting, "restarting"),
3179 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3180 ] {
3181 let wire = serde_json::to_string(&value).unwrap();
3182 assert_eq!(wire, format!("\"{expected}\""));
3183 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3184 assert_eq!(decoded, value);
3185 }
3186 }
3187
3188 #[test]
3189 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3190 let entry = SupervisorEntry::new(
3191 "waiting-module",
3192 "starting",
3193 true,
3194 false,
3195 SupervisorHealthStatus::Unknown,
3196 );
3197 let old_wire = serde_json::to_value(&entry).unwrap();
3198 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3199 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3200 assert_eq!(decoded.waiting_for_previous_pid, None);
3201 let entry = entry.with_waiting_for_previous_pid(Some(42));
3202 let wire = serde_json::to_value(&entry).unwrap();
3203 assert_eq!(wire["waiting_for_previous_pid"], 42);
3204 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3205 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3206 }
3207
3208 #[test]
3209 fn diagnostic_string_enums_reject_non_string_bodies() {
3210 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3211 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3212 }
3213
3214 #[test]
3215 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3216 let body = serde_json::json!({
3217 "op": "supervisor.provenance",
3218 "daemon": {
3219 "daemon_build": {},
3220 "daemon_observed": {
3221 "running_image": {
3222 "status": "unavailable",
3223 "reason": "not_running"
3224 }
3225 }
3226 },
3227 "modules": [
3228 {
3229 "module_id": "future",
3230 "module_declared": { "status": "unverifiable" },
3231 "daemon_observed": {
3232 "running_image": {
3233 "status": "unavailable",
3234 "reason": "future_reason"
3235 }
3236 }
3237 },
3238 {
3239 "module_id": "healthy-a",
3240 "module_declared": { "status": "unverifiable" },
3241 "daemon_observed": {
3242 "running_image": {
3243 "status": "match",
3244 "evidence": {
3245 "method": "linux_proc_sha256",
3246 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3247 }
3248 }
3249 }
3250 },
3251 {
3252 "module_id": "healthy-b",
3253 "module_declared": { "status": "unverifiable" },
3254 "daemon_observed": {
3255 "running_image": {
3256 "status": "unavailable",
3257 "reason": "unsupported_platform"
3258 }
3259 }
3260 }
3261 ]
3262 });
3263
3264 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3265 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3266 panic!("decoded wrong response variant");
3267 };
3268 assert_eq!(modules.len(), 3);
3269 assert_eq!(modules[0].module_id, "future");
3270 assert_eq!(
3271 modules[0].daemon_observed.running_image,
3272 RunningImageAgreement::Unavailable {
3273 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3274 }
3275 );
3276 assert_eq!(modules[1].module_id, "healthy-a");
3277 assert_eq!(modules[2].module_id, "healthy-b");
3278 }
3279
3280 #[test]
3281 fn tagged_unknown_values_retain_tag_and_body() {
3282 macro_rules! assert_unknown_round_trip {
3283 ($ty:ident, $field:literal, $value:expr) => {
3284 let value = $value;
3285 let wire = serde_json::to_string(&value).unwrap();
3286 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3287 match decoded {
3288 $ty::Unknown { tag, body } => {
3289 assert_eq!(tag, value[$field].as_str().unwrap());
3290 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3291 }
3292 _ => panic!("decoded known variant"),
3293 }
3294 };
3295 }
3296
3297 assert_unknown_round_trip!(
3298 ModuleDeclaredProvenance,
3299 "status",
3300 serde_json::json!({"status": "future", "build": {"version": 7}})
3301 );
3302 assert_unknown_round_trip!(
3303 RunningImageAgreement,
3304 "status",
3305 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3306 );
3307 assert_unknown_round_trip!(
3308 RunningImageEvidence,
3309 "method",
3310 serde_json::json!({"method": "future", "digest": "abc"})
3311 );
3312 assert_unknown_round_trip!(
3313 SupervisorRouteConsumer,
3314 "kind",
3315 serde_json::json!({"kind": "future", "module_id": "m"})
3316 );
3317 assert_unknown_round_trip!(
3318 StderrCaptureState,
3319 "state",
3320 serde_json::json!({"state": "future", "reason": "because"})
3321 );
3322 assert_unknown_round_trip!(
3323 StderrTailEntry,
3324 "kind",
3325 serde_json::json!({"kind": "future", "text": "line"})
3326 );
3327 assert_unknown_round_trip!(
3328 ChildResourceUsage,
3329 "status",
3330 serde_json::json!({"status": "future", "memory_bytes": 1})
3331 );
3332 }
3333
3334 #[test]
3335 fn child_resource_usage_round_trips_both_known_states() {
3336 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3337 memory_bytes: 0,
3338 memory_kind: ChildMemoryKind::ResidentSet,
3339 swap_bytes: Some(0),
3340 cpu_user_ms: 0,
3341 cpu_system_ms: 0,
3342 });
3343 let wire = serde_json::to_value(&measured).unwrap();
3344 assert_eq!(
3345 wire,
3346 serde_json::json!({
3347 "status": "measured",
3348 "memory_bytes": 0,
3349 "memory_kind": "resident_set",
3350 "swap_bytes": 0,
3351 "cpu_user_ms": 0,
3352 "cpu_system_ms": 0
3353 })
3354 );
3355 assert_eq!(
3356 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3357 measured
3358 );
3359
3360 let unavailable = ChildResourceUsage::Unavailable {
3361 reason: ChildResourceUnavailableReason::NotRunning,
3362 };
3363 let wire = serde_json::to_value(&unavailable).unwrap();
3364 assert_eq!(
3365 wire,
3366 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3367 );
3368 assert_eq!(
3369 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3370 unavailable
3371 );
3372 }
3373
3374 #[test]
3375 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3376 let stamped: StderrTailEntry = serde_json::from_str(
3380 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3381 )
3382 .unwrap();
3383 assert_eq!(
3384 stamped,
3385 StderrTailEntry::Line {
3386 text: "boom".to_string(),
3387 truncated: true,
3388 at_ms: Some(1_789_801_440_685),
3389 }
3390 );
3391 let unstamped: StderrTailEntry =
3392 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3393 assert_eq!(
3394 unstamped,
3395 StderrTailEntry::Line {
3396 text: "boom".to_string(),
3397 truncated: false,
3398 at_ms: None,
3399 }
3400 );
3401 assert_eq!(
3404 serde_json::to_string(&unstamped).unwrap(),
3405 r#"{"kind":"line","text":"boom"}"#
3406 );
3407 assert_eq!(
3408 serde_json::to_value(&stamped).unwrap()["at_ms"],
3409 serde_json::json!(1_789_801_440_685u64)
3410 );
3411 }
3412
3413 #[test]
3414 fn tagged_unknown_values_round_trip_the_original_json() {
3415 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3416 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3417 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3418 }
3419
3420 #[test]
3421 fn tagged_unknown_values_round_trip_trailing_tag() {
3422 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3423 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3424 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3425
3426 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3427 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3428 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3429 }
3430
3431 #[test]
3432 fn tagged_unknown_values_round_trip_middle_tag() {
3433 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3434 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3435 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3436
3437 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3438 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3439 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3440 }
3441
3442 #[test]
3443 fn tagged_unknown_values_round_trip_deep_payload() {
3444 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3445 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3446 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3447
3448 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3449 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3450 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3451 }
3452
3453 #[test]
3454 fn tagged_unknown_values_reject_non_object_bodies() {
3455 for wire in ["42", r#""future""#, "[]"] {
3456 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3457 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3458 }
3459 }
3460
3461 #[test]
3462 fn duplicate_discriminators_reject_without_panicking() {
3463 assert_eq!(
3464 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3465 .unwrap(),
3466 ModuleDeclaredProvenance::Unverifiable
3467 );
3468 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3469 .unwrap()
3470 {
3471 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3472 _ => panic!("future discriminator decoded as a known variant"),
3473 }
3474
3475 let wires = [
3476 r#"{"status":"reported","status":"unverifiable"}"#,
3477 r#"{"status":"unverifiable","status":"reported"}"#,
3478 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3479 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3480 ];
3481
3482 for wire in wires {
3483 let result =
3484 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3485 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3486 assert!(
3487 result.unwrap().is_err(),
3488 "duplicate discriminator decoded: {wire}"
3489 );
3490 }
3491
3492 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3493 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3494 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3495 assert!(
3496 result.unwrap().is_err(),
3497 "duplicate discriminator decoded: {wire}"
3498 );
3499 }
3500
3501 #[test]
3502 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3503 let known_wire =
3504 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3505 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3506 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3507
3508 for wire in [
3509 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3510 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3511 ] {
3512 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3513 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3514 }
3515
3516 for wire in [
3517 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3518 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3519 ] {
3520 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3521 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3522 }
3523
3524 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3525 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3526 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3527
3528 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3529 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3530 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3531 }
3532
3533 #[test]
3534 fn tagged_unknown_member_does_not_discard_known_siblings() {
3535 let body = serde_json::json!({
3536 "modules": [{
3537 "module_id": "target",
3538 "routes": [
3539 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3540 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3541 ]
3542 }]
3543 });
3544 let decoded: ClientControlResponse = serde_json::from_value(
3545 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3546 )
3547 .unwrap();
3548 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3549 panic!("decoded wrong response variant");
3550 };
3551 assert_eq!(modules[0].routes.len(), 2);
3552 assert_eq!(
3553 modules[0].routes[1].consumer,
3554 SupervisorRouteConsumer::Direct { connection_id: 7 }
3555 );
3556 }
3557}
3558
3559#[cfg(test)]
3560mod launch_nonce_redaction_tests {
3561 use super::*;
3562
3563 const NONCE: &str = "nonce-f00dfeed1234abcd";
3564
3565 fn identity() -> ConsumerIdentity {
3566 ConsumerIdentity {
3567 module_id: "wernicke".to_string(),
3568 launch_nonce: NONCE.to_string(),
3569 }
3570 }
3571
3572 #[test]
3573 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3574 let printed = format!("{:?}", identity());
3575 assert!(printed.contains("wernicke"), "{printed}");
3576 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3577 }
3578
3579 #[test]
3580 fn route_open_request_debug_never_prints_the_nonce() {
3581 let request = ClientControlRequest::RouteOpen {
3582 busy_refusals: None,
3583 target: subc_protocol::RouteTarget::ToolProvider {
3584 module_id: "broca".to_string(),
3585 },
3586 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
3587 consumer_identity: Some(identity()),
3588 consumer_capabilities: None,
3589 role_versions: None,
3590 admission_facts: None,
3591 scope: None,
3592 };
3593 let printed = format!("{request:?}");
3594 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3595 }
3596}