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, skip_serializing_if = "Option::is_none")]
2007 pub display_name: Option<String>,
2008 #[serde(default = "default_true")]
2019 pub ready: bool,
2020 #[serde(default, skip_serializing_if = "Option::is_none")]
2024 pub not_ready: Option<NotReadyReason>,
2025 #[serde(default, skip_serializing_if = "Option::is_none")]
2046 pub module_version: Option<String>,
2047 #[serde(default, skip_serializing_if = "Option::is_none")]
2050 pub provenance: Option<ManifestProvenance>,
2051 pub roles: Vec<ProviderRole>,
2052 pub control_ops: Vec<String>,
2053 #[serde(default, skip_serializing_if = "Option::is_none")]
2058 pub capabilities: Option<CapabilityDeclarations>,
2059 #[serde(default, skip_serializing_if = "Option::is_none")]
2062 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2063 #[serde(default, skip_serializing_if = "Option::is_none")]
2067 pub events: Option<Vec<EventDeclaration>>,
2068 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2071 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2072 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2075 pub operation_payload: BTreeMap<String, OperationPayload>,
2076 #[serde(default, skip_serializing_if = "Option::is_none")]
2082 pub flow_operations: Option<Vec<String>>,
2083 #[serde(default, skip_serializing_if = "Option::is_none")]
2089 pub confirm_operations: Option<Vec<String>>,
2090 #[serde(default, skip_serializing_if = "Option::is_none")]
2093 pub rich_ui: Option<RichUiDescriptor>,
2094 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2097 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2098 #[serde(default, skip_serializing_if = "is_false")]
2101 pub nonce_verified: bool,
2102}
2103
2104impl CatalogEntry {
2105 #[must_use]
2107 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2108 self.display_name = display_name;
2109 self
2110 }
2111
2112 #[must_use]
2114 pub fn new(
2115 module_id: impl Into<String>,
2116 roles: Vec<ProviderRole>,
2117 control_ops: Vec<String>,
2118 ) -> Self {
2119 Self {
2120 module_id: module_id.into(),
2121 ready: default_true(),
2122 display_name: None,
2123 not_ready: None,
2124 module_version: None,
2125 provenance: None,
2126 roles,
2127 control_ops,
2128 capabilities: None,
2129 self_signals: None,
2130 events: None,
2131 operation_delivery: BTreeMap::new(),
2132 operation_payload: BTreeMap::new(),
2133 flow_operations: None,
2134 confirm_operations: None,
2135 rich_ui: None,
2136 role_declarations: BTreeMap::new(),
2137 nonce_verified: false,
2138 }
2139 }
2140
2141 #[must_use]
2143 pub fn with_operation_payload(
2144 mut self,
2145 operation_payload: BTreeMap<String, OperationPayload>,
2146 ) -> Self {
2147 self.operation_payload = operation_payload;
2148 self
2149 }
2150
2151 #[must_use]
2154 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2155 self.flow_operations = flow_operations;
2156 self
2157 }
2158
2159 #[must_use]
2162 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2163 self.confirm_operations = confirm_operations;
2164 self
2165 }
2166
2167 #[must_use]
2169 pub fn with_ready(mut self, ready: bool) -> Self {
2170 self.ready = ready;
2171 self
2172 }
2173
2174 #[must_use]
2176 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2177 self.not_ready = not_ready;
2178 self
2179 }
2180
2181 #[must_use]
2183 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2184 self.module_version = module_version;
2185 self
2186 }
2187
2188 #[must_use]
2190 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2191 self.provenance = provenance;
2192 self
2193 }
2194
2195 #[must_use]
2197 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2198 self.capabilities = capabilities;
2199 self
2200 }
2201
2202 #[must_use]
2204 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2205 self.self_signals = self_signals;
2206 self
2207 }
2208
2209 #[must_use]
2211 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2212 self.events = events;
2213 self
2214 }
2215
2216 #[must_use]
2219 pub fn with_operation_delivery(
2220 mut self,
2221 operation_delivery: BTreeMap<String, OperationDelivery>,
2222 ) -> Self {
2223 self.operation_delivery = operation_delivery;
2224 self
2225 }
2226
2227 #[must_use]
2229 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2230 self.rich_ui = rich_ui;
2231 self
2232 }
2233
2234 #[must_use]
2236 pub fn with_role_declarations(
2237 mut self,
2238 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2239 ) -> Self {
2240 self.role_declarations = role_declarations;
2241 self
2242 }
2243
2244 #[must_use]
2247 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2248 self.nonce_verified = nonce_verified;
2249 self
2250 }
2251}
2252
2253fn is_false(value: &bool) -> bool {
2254 !value
2255}
2256
2257#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2259pub struct NotReadyReason {
2260 pub reason: String,
2265 #[serde(default, skip_serializing_if = "Option::is_none")]
2268 pub capability: Option<String>,
2269}
2270
2271impl NotReadyReason {
2272 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2273 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2274}
2275
2276#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2277pub struct CapabilityRequirementStatus {
2278 pub consumer: String,
2279 pub capability: String,
2280 pub need: String,
2281 pub verdict: String,
2282 pub episode_seq: u64,
2283 pub config_satisfiable: bool,
2284 pub runtime_available: bool,
2285 pub detail: String,
2286}
2287
2288#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2289pub struct SupervisorRescanResult {
2290 pub added: Vec<String>,
2291 pub removed: Vec<String>,
2292 pub changed_pending_reload: Vec<String>,
2293 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2306 pub enabled_changes: Vec<String>,
2307 pub unchanged: u32,
2308 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2316 pub preview: bool,
2317 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2335 pub restart_required: Vec<String>,
2336 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2340 pub capability_warnings: Vec<String>,
2341 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2348 pub module_actions: Vec<RescanModuleAction>,
2349 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2353 pub earlier_pending: Vec<String>,
2354 #[serde(default, skip_serializing_if = "Option::is_none")]
2357 pub expect: Option<RescanExpect>,
2358}
2359
2360#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2376#[serde(rename_all = "snake_case")]
2377pub enum ModuleProtocol {
2378 #[default]
2382 Subc,
2383 None,
2392}
2393
2394#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2406#[non_exhaustive]
2407pub struct SupervisorEntry {
2408 #[serde(default, skip_serializing_if = "Option::is_none")]
2411 pub waiting_for_previous_pid: Option<u32>,
2412 pub module_id: String,
2413 pub state: String,
2414 #[serde(default, skip_serializing_if = "Option::is_none")]
2418 pub next_retry_at_ms: Option<u64>,
2419 pub enabled: bool,
2420 #[serde(default, skip_serializing_if = "Option::is_none")]
2423 pub configured_enabled: Option<bool>,
2424 pub live: bool,
2434 #[serde(default)]
2438 pub protocol: ModuleProtocol,
2439 #[serde(default, skip_serializing_if = "Option::is_none")]
2442 pub launch_nonce_env: Option<bool>,
2443 #[serde(default, skip_serializing_if = "Option::is_none")]
2449 pub launch_nonce_source: Option<String>,
2450 pub health: SupervisorHealthStatus,
2451 #[serde(default, skip_serializing_if = "Option::is_none")]
2454 pub pending_reload: Option<PendingReloadVerdict>,
2455 #[serde(default)]
2461 pub last_probe_ms: Option<u64>,
2462 #[serde(default, skip_serializing_if = "Option::is_none")]
2466 pub last_exit_code: Option<i32>,
2467 #[serde(default, skip_serializing_if = "Option::is_none")]
2471 pub last_exit_signal: Option<i32>,
2472 #[serde(default, skip_serializing_if = "Option::is_none")]
2476 pub last_exit_ms: Option<u64>,
2477 #[serde(default, skip_serializing_if = "Option::is_none")]
2480 pub last_exit_kind: Option<TerminalExitKind>,
2481 #[serde(default, skip_serializing_if = "Option::is_none")]
2498 pub restart_count: Option<u32>,
2499 #[serde(default, skip_serializing_if = "Option::is_none")]
2502 pub max_restarts: Option<u32>,
2503 #[serde(default, skip_serializing_if = "Option::is_none")]
2506 pub lifetime_restarts: Option<u32>,
2507 #[serde(default, skip_serializing_if = "Option::is_none")]
2511 pub spawn_generation: Option<u64>,
2512 #[serde(default, skip_serializing_if = "Option::is_none")]
2522 pub restart_window_secs: Option<u64>,
2523 #[serde(default, skip_serializing_if = "Option::is_none")]
2527 pub drain_timeout_ms: Option<u64>,
2528 #[serde(default, skip_serializing_if = "Option::is_none")]
2531 pub restart_backoff_ms: Option<u64>,
2532 #[serde(default, skip_serializing_if = "Option::is_none")]
2535 pub restart_max_backoff_ms: Option<u64>,
2536 #[serde(default, skip_serializing_if = "Option::is_none")]
2549 pub resources: Option<ChildResourceUsage>,
2550 #[serde(default, skip_serializing_if = "Option::is_none")]
2553 pub subtree: Option<SubtreeReading>,
2554}
2555
2556impl SupervisorEntry {
2557 #[must_use]
2559 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2560 self.next_retry_at_ms = next_retry_at_ms;
2561 self
2562 }
2563
2564 #[must_use]
2566 pub fn new(
2567 module_id: impl Into<String>,
2568 state: impl Into<String>,
2569 enabled: bool,
2570 live: bool,
2571 health: SupervisorHealthStatus,
2572 ) -> Self {
2573 Self {
2574 module_id: module_id.into(),
2575 state: state.into(),
2576 next_retry_at_ms: None,
2577 waiting_for_previous_pid: None,
2578 enabled,
2579 configured_enabled: None,
2580 live,
2581 protocol: ModuleProtocol::default(),
2582 launch_nonce_env: None,
2583 launch_nonce_source: None,
2584 health,
2585 pending_reload: None,
2586 last_probe_ms: None,
2587 last_exit_code: None,
2588 last_exit_signal: None,
2589 last_exit_ms: None,
2590 last_exit_kind: None,
2591 restart_count: None,
2592 max_restarts: None,
2593 lifetime_restarts: None,
2594 spawn_generation: None,
2595 restart_window_secs: None,
2596 drain_timeout_ms: None,
2597 restart_backoff_ms: None,
2598 restart_max_backoff_ms: None,
2599 resources: None,
2600 subtree: None,
2601 }
2602 }
2603
2604 #[must_use]
2606 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2607 self.protocol = protocol;
2608 self
2609 }
2610
2611 #[must_use]
2613 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2614 self.configured_enabled = configured_enabled;
2615 self
2616 }
2617
2618 #[must_use]
2620 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2621 self.launch_nonce_env = launch_nonce_env;
2622 self
2623 }
2624
2625 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2626 self.launch_nonce_source = source;
2627 self
2628 }
2629
2630 #[must_use]
2631 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2632 self.waiting_for_previous_pid = pid;
2633 self
2634 }
2635
2636 #[must_use]
2638 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2639 self.pending_reload = pending_reload;
2640 self
2641 }
2642
2643 #[must_use]
2645 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2646 self.last_probe_ms = last_probe_ms;
2647 self
2648 }
2649
2650 #[must_use]
2652 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2653 self.last_exit_code = last_exit_code;
2654 self
2655 }
2656
2657 #[must_use]
2659 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2660 self.last_exit_signal = last_exit_signal;
2661 self
2662 }
2663
2664 #[must_use]
2666 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2667 self.last_exit_ms = last_exit_ms;
2668 self
2669 }
2670
2671 #[must_use]
2673 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2674 self.last_exit_kind = last_exit_kind;
2675 self
2676 }
2677
2678 #[must_use]
2680 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2681 self.restart_count = restart_count;
2682 self
2683 }
2684
2685 #[must_use]
2687 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2688 self.max_restarts = max_restarts;
2689 self
2690 }
2691
2692 #[must_use]
2694 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2695 self.lifetime_restarts = lifetime_restarts;
2696 self
2697 }
2698
2699 #[must_use]
2701 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2702 self.spawn_generation = spawn_generation;
2703 self
2704 }
2705
2706 #[must_use]
2708 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2709 self.restart_window_secs = restart_window_secs;
2710 self
2711 }
2712
2713 #[must_use]
2715 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2716 self.drain_timeout_ms = drain_timeout_ms;
2717 self
2718 }
2719
2720 #[must_use]
2722 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2723 self.restart_backoff_ms = restart_backoff_ms;
2724 self
2725 }
2726
2727 #[must_use]
2729 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2730 self.restart_max_backoff_ms = restart_max_backoff_ms;
2731 self
2732 }
2733
2734 #[must_use]
2736 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2737 self.resources = resources;
2738 self
2739 }
2740
2741 #[must_use]
2743 pub fn with_subtree(mut self, subtree: Option<SubtreeReading>) -> Self {
2744 self.subtree = subtree;
2745 self
2746 }
2747}
2748
2749#[derive(Debug, Clone, PartialEq)]
2752pub enum ChildResourceUsage {
2753 Measured(ChildResourceReading),
2754 Unavailable {
2755 reason: ChildResourceUnavailableReason,
2756 },
2757 Unknown {
2760 tag: String,
2761 body: OrderedJsonObject,
2762 },
2763}
2764
2765#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2767pub struct ChildResourceReading {
2768 pub memory_bytes: u64,
2771 pub memory_kind: ChildMemoryKind,
2772 #[serde(default, skip_serializing_if = "Option::is_none")]
2775 pub swap_bytes: Option<u64>,
2776 pub cpu_user_ms: u64,
2780 pub cpu_system_ms: u64,
2783}
2784
2785open_string_enum! {
2786 ChildMemoryKind {
2788 PhysFootprint => "phys_footprint",
2792 ResidentSet => "resident_set",
2795 WindowsWorkingSet => "windows_working_set",
2798 }
2799}
2800
2801open_string_enum! {
2802 ChildResourceUnavailableReason {
2804 NotRunning => "not_running",
2806 UnsupportedPlatform => "unsupported_platform",
2808 Unreadable => "unreadable",
2811 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2814 }
2815}
2816
2817#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2818#[serde(rename_all = "snake_case")]
2819pub enum SupervisorHealthStatus {
2820 Ok,
2821 Degraded,
2822 Failing,
2823 Unresponsive,
2824 Unknown,
2825}
2826
2827#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2828pub struct SupervisorHealthEntry {
2829 pub module_id: String,
2830 pub status: SupervisorHealthStatus,
2831 #[serde(default, skip_serializing_if = "Option::is_none")]
2837 pub detail: Option<String>,
2838 #[serde(default, skip_serializing_if = "Option::is_none")]
2843 pub metrics: Option<serde_json::Value>,
2844 pub consecutive_failures: u32,
2845 #[serde(default)]
2848 pub late_answer_count: u64,
2849 #[serde(default, skip_serializing_if = "Option::is_none")]
2851 pub last_late_answer_latency_ms: Option<u64>,
2852 #[serde(default)]
2857 pub last_action: Option<String>,
2858 #[serde(default)]
2861 pub last_action_ms: Option<u64>,
2862 #[serde(default, skip_serializing_if = "Option::is_none")]
2875 pub last_probe_ms: Option<u64>,
2876}
2877
2878#[cfg(test)]
2879mod tests {
2880 #[test]
2881 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2882 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2883 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2884 assert_eq!(decoded.configured_enabled, None);
2885 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2886 }
2887
2888 #[test]
2889 fn configured_enabled_values_round_trip_in_list() {
2890 for enabled in [false, true] {
2891 let entry = SupervisorEntry::new(
2892 "provider",
2893 "running",
2894 true,
2895 true,
2896 SupervisorHealthStatus::Unknown,
2897 )
2898 .with_configured_enabled(Some(enabled));
2899 let entry_json = serde_json::to_value(&entry).unwrap();
2900 assert_eq!(entry_json["configured_enabled"], enabled);
2901 assert_eq!(
2902 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
2903 entry
2904 );
2905 }
2906 }
2907
2908 #[test]
2909 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2910 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2911 volume_serial_number: u64::MAX,
2912 file_id: [
2913 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2914 ],
2915 };
2916 let agreement = super::RunningImageAgreement::Match { evidence };
2917 let encoded = serde_json::to_string(&agreement).unwrap();
2918 assert!(encoded.contains("windows_spawn_file_id"));
2919 assert_eq!(
2920 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
2921 agreement
2922 );
2923 }
2924
2925 #[test]
2926 fn unix_running_image_evidence_keeps_original_wire_bytes() {
2927 assert_eq!(
2928 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
2929 device: 7,
2930 inode: 11
2931 })
2932 .unwrap(),
2933 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
2934 );
2935 assert_eq!(
2936 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
2937 digest: "abc".to_owned()
2938 })
2939 .unwrap(),
2940 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
2941 );
2942 }
2943 use super::*;
2944 use subc_protocol::{BindIdentity, RouteTarget};
2945
2946 #[test]
2947 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2948 let entry = TerminalEntry {
2949 daemon_incarnation: Some("daemon-before-restart".into()),
2950 exit_code: Some(1),
2951 exit_signal: None,
2952 at_ms: 1_700_000_000_123,
2953 disposition: TerminalDisposition::Restarting,
2954 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2955 disposition_detail: None,
2956 };
2957 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2958 assert_eq!(
2959 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2960 ["exit_kind"],
2961 "deliberate_severance"
2962 );
2963
2964 #[derive(serde::Deserialize)]
2965 struct LegacyTerminalEntry {
2966 exit_code: Option<i32>,
2967 exit_signal: Option<i32>,
2968 at_ms: u64,
2969 disposition: TerminalDisposition,
2970 }
2971
2972 let decoded: LegacyTerminalEntry =
2973 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2974 assert_eq!(decoded.exit_code, Some(1));
2975 assert_eq!(decoded.exit_signal, None);
2976 assert_eq!(decoded.at_ms, 1_700_000_000_123);
2977 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
2978
2979 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
2980 let future: TerminalEntry =
2981 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
2982 assert_eq!(
2983 future.exit_kind,
2984 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
2985 );
2986 }
2987
2988 #[test]
2989 fn terminal_incarnation_is_optional_for_older_daemons() {
2990 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
2991 "at_ms": 123,
2992 "disposition": "stopped"
2993 }))
2994 .unwrap();
2995 let encoded = serde_json::to_value(&entry).unwrap();
2996 assert_eq!(
2997 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
2998 (None, None)
2999 );
3000 }
3001
3002 #[test]
3003 fn route_poll_uses_kind_field() {
3004 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3005 route_channel: 7,
3006 route_epoch: 11,
3007 kind: PollKind::Status,
3008 })
3009 .unwrap();
3010
3011 assert_eq!(body["op"], "route.poll");
3012 assert_eq!(body["route_epoch"], 11);
3013 assert_eq!(body["kind"], "status");
3014 assert!(body.get("op").is_some());
3015 }
3016
3017 #[test]
3018 fn route_open_is_internally_tagged() {
3019 let request = ClientControlRequest::RouteOpen {
3020 busy_refusals: None,
3021 target: RouteTarget::ToolProvider {
3022 module_id: "aft".to_string(),
3023 },
3024 identity: BindIdentity::new("opencode", "session-1"),
3025 consumer_identity: None,
3026 consumer_capabilities: None,
3027 role_versions: None,
3028 admission_facts: None,
3029 scope: None,
3030 };
3031
3032 let body = serde_json::to_value(request).unwrap();
3033 assert_eq!(body["op"], "route.open");
3034 assert_eq!(body["target"]["kind"], "tool_provider");
3035 assert!(body.get("consumer_identity").is_none());
3036 assert!(body.get("consumer_capabilities").is_none());
3037 assert!(body.get("role_versions").is_none());
3038 }
3039
3040 #[test]
3041 fn route_open_without_optional_fields_still_decodes() {
3042 let body = serde_json::json!({
3043 "op": "route.open",
3044 "target": { "kind": "tool_provider", "module_id": "aft" },
3045 "identity": {
3046 "project_root": "/tmp/project",
3047 "harness": "opencode",
3048 "session": "session-1"
3049 }
3050 });
3051
3052 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3053 let ClientControlRequest::RouteOpen {
3054 consumer_identity,
3055 consumer_capabilities,
3056 role_versions,
3057 admission_facts,
3058 ..
3059 } = decoded
3060 else {
3061 panic!("decoded wrong request variant");
3062 };
3063 assert_eq!(consumer_identity, None);
3064 assert_eq!(consumer_capabilities, None);
3065 assert_eq!(role_versions, None);
3066 assert_eq!(admission_facts, None);
3067 }
3068
3069 #[test]
3070 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3071 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3072 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3073 match decoded {
3074 ClientControlPush::RouteClosed {
3075 excluded_subscriptions,
3076 terminal,
3077 ..
3078 } => {
3079 assert_eq!(excluded_subscriptions, 0);
3080 assert_eq!(terminal, None);
3081 }
3082 other => panic!("unexpected push: {other:?}"),
3083 }
3084 assert!(!serde_json::to_string(&decoded)
3085 .unwrap()
3086 .contains("terminal"));
3087 }
3088
3089 #[test]
3090 fn old_route_closed_decoder_ignores_new_terminal_field() {
3091 #[derive(serde::Deserialize)]
3092 #[serde(tag = "op")]
3093 enum LegacyClientControlPush {
3094 #[serde(rename = "route.closed")]
3095 RouteClosed {
3096 module_id: String,
3097 reason: RouteCloseReason,
3098 drained: bool,
3099 abandoned: u32,
3100 },
3101 }
3102
3103 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3104 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3105 match decoded {
3106 LegacyClientControlPush::RouteClosed {
3107 module_id,
3108 reason,
3109 drained,
3110 abandoned,
3111 } => {
3112 assert_eq!(module_id, "aft-tools");
3113 assert_eq!(reason, RouteCloseReason::Crash);
3114 assert!(!drained);
3115 assert_eq!(abandoned, 0);
3116 }
3117 }
3118 }
3119
3120 #[test]
3121 fn supervisor_routes_is_a_control_plane_request() {
3122 let body = serde_json::json!({
3123 "op": "supervisor.routes",
3124 "module_id": "aft"
3125 });
3126
3127 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3128 assert_eq!(serde_json::to_value(request).unwrap(), body);
3129 }
3130
3131 #[test]
3132 fn diagnostic_string_enums_retain_unknown_wire_values() {
3133 let reason: RunningImageUnavailableReason =
3134 serde_json::from_str("\"future_reason\"").unwrap();
3135 let disposition: TerminalDisposition =
3136 serde_json::from_str("\"future_disposition\"").unwrap();
3137
3138 assert_eq!(
3139 reason,
3140 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3141 );
3142 assert_eq!(
3143 disposition,
3144 TerminalDisposition::Unknown("future_disposition".to_string())
3145 );
3146 }
3147
3148 #[test]
3149 fn diagnostic_string_enums_preserve_existing_wire_names() {
3150 let names = [
3151 (RunningImageUnavailableReason::NotRunning, "not_running"),
3152 (
3153 RunningImageUnavailableReason::UnsupportedPlatform,
3154 "unsupported_platform",
3155 ),
3156 (
3157 RunningImageUnavailableReason::RunningExecutableUnreadable,
3158 "running_executable_unreadable",
3159 ),
3160 (
3161 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3162 "running_executable_permission_denied",
3163 ),
3164 (
3165 RunningImageUnavailableReason::ProcessHidden,
3166 "process_hidden",
3167 ),
3168 (
3169 RunningImageUnavailableReason::SpawnedPathUnreadable,
3170 "spawned_path_unreadable",
3171 ),
3172 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3173 (
3174 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3175 "process_identity_unconfirmed",
3176 ),
3177 ];
3178 for (value, expected) in names {
3179 let wire = serde_json::to_string(&value).unwrap();
3180 assert_eq!(wire, format!("\"{expected}\""));
3181 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3182 assert_eq!(decoded, value);
3183 }
3184
3185 for (value, expected) in [
3186 (TerminalDisposition::Stopped, "stopped"),
3187 (TerminalDisposition::Disabled, "disabled"),
3188 (TerminalDisposition::Failed, "failed"),
3189 (TerminalDisposition::Restarting, "restarting"),
3190 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3191 ] {
3192 let wire = serde_json::to_string(&value).unwrap();
3193 assert_eq!(wire, format!("\"{expected}\""));
3194 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3195 assert_eq!(decoded, value);
3196 }
3197 }
3198
3199 #[test]
3200 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3201 let entry = SupervisorEntry::new(
3202 "waiting-module",
3203 "starting",
3204 true,
3205 false,
3206 SupervisorHealthStatus::Unknown,
3207 );
3208 let old_wire = serde_json::to_value(&entry).unwrap();
3209 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3210 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3211 assert_eq!(decoded.waiting_for_previous_pid, None);
3212 let entry = entry.with_waiting_for_previous_pid(Some(42));
3213 let wire = serde_json::to_value(&entry).unwrap();
3214 assert_eq!(wire["waiting_for_previous_pid"], 42);
3215 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3216 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3217 }
3218
3219 #[test]
3220 fn diagnostic_string_enums_reject_non_string_bodies() {
3221 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3222 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3223 }
3224
3225 #[test]
3226 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3227 let body = serde_json::json!({
3228 "op": "supervisor.provenance",
3229 "daemon": {
3230 "daemon_build": {},
3231 "daemon_observed": {
3232 "running_image": {
3233 "status": "unavailable",
3234 "reason": "not_running"
3235 }
3236 }
3237 },
3238 "modules": [
3239 {
3240 "module_id": "future",
3241 "module_declared": { "status": "unverifiable" },
3242 "daemon_observed": {
3243 "running_image": {
3244 "status": "unavailable",
3245 "reason": "future_reason"
3246 }
3247 }
3248 },
3249 {
3250 "module_id": "healthy-a",
3251 "module_declared": { "status": "unverifiable" },
3252 "daemon_observed": {
3253 "running_image": {
3254 "status": "match",
3255 "evidence": {
3256 "method": "linux_proc_sha256",
3257 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3258 }
3259 }
3260 }
3261 },
3262 {
3263 "module_id": "healthy-b",
3264 "module_declared": { "status": "unverifiable" },
3265 "daemon_observed": {
3266 "running_image": {
3267 "status": "unavailable",
3268 "reason": "unsupported_platform"
3269 }
3270 }
3271 }
3272 ]
3273 });
3274
3275 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3276 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3277 panic!("decoded wrong response variant");
3278 };
3279 assert_eq!(modules.len(), 3);
3280 assert_eq!(modules[0].module_id, "future");
3281 assert_eq!(
3282 modules[0].daemon_observed.running_image,
3283 RunningImageAgreement::Unavailable {
3284 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3285 }
3286 );
3287 assert_eq!(modules[1].module_id, "healthy-a");
3288 assert_eq!(modules[2].module_id, "healthy-b");
3289 }
3290
3291 #[test]
3292 fn tagged_unknown_values_retain_tag_and_body() {
3293 macro_rules! assert_unknown_round_trip {
3294 ($ty:ident, $field:literal, $value:expr) => {
3295 let value = $value;
3296 let wire = serde_json::to_string(&value).unwrap();
3297 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3298 match decoded {
3299 $ty::Unknown { tag, body } => {
3300 assert_eq!(tag, value[$field].as_str().unwrap());
3301 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3302 }
3303 _ => panic!("decoded known variant"),
3304 }
3305 };
3306 }
3307
3308 assert_unknown_round_trip!(
3309 ModuleDeclaredProvenance,
3310 "status",
3311 serde_json::json!({"status": "future", "build": {"version": 7}})
3312 );
3313 assert_unknown_round_trip!(
3314 RunningImageAgreement,
3315 "status",
3316 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3317 );
3318 assert_unknown_round_trip!(
3319 RunningImageEvidence,
3320 "method",
3321 serde_json::json!({"method": "future", "digest": "abc"})
3322 );
3323 assert_unknown_round_trip!(
3324 SupervisorRouteConsumer,
3325 "kind",
3326 serde_json::json!({"kind": "future", "module_id": "m"})
3327 );
3328 assert_unknown_round_trip!(
3329 StderrCaptureState,
3330 "state",
3331 serde_json::json!({"state": "future", "reason": "because"})
3332 );
3333 assert_unknown_round_trip!(
3334 StderrTailEntry,
3335 "kind",
3336 serde_json::json!({"kind": "future", "text": "line"})
3337 );
3338 assert_unknown_round_trip!(
3339 ChildResourceUsage,
3340 "status",
3341 serde_json::json!({"status": "future", "memory_bytes": 1})
3342 );
3343 }
3344
3345 #[test]
3346 fn child_resource_usage_round_trips_both_known_states() {
3347 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3348 memory_bytes: 0,
3349 memory_kind: ChildMemoryKind::ResidentSet,
3350 swap_bytes: Some(0),
3351 cpu_user_ms: 0,
3352 cpu_system_ms: 0,
3353 });
3354 let wire = serde_json::to_value(&measured).unwrap();
3355 assert_eq!(
3356 wire,
3357 serde_json::json!({
3358 "status": "measured",
3359 "memory_bytes": 0,
3360 "memory_kind": "resident_set",
3361 "swap_bytes": 0,
3362 "cpu_user_ms": 0,
3363 "cpu_system_ms": 0
3364 })
3365 );
3366 assert_eq!(
3367 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3368 measured
3369 );
3370
3371 let unavailable = ChildResourceUsage::Unavailable {
3372 reason: ChildResourceUnavailableReason::NotRunning,
3373 };
3374 let wire = serde_json::to_value(&unavailable).unwrap();
3375 assert_eq!(
3376 wire,
3377 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3378 );
3379 assert_eq!(
3380 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3381 unavailable
3382 );
3383 }
3384
3385 #[test]
3386 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3387 let stamped: StderrTailEntry = serde_json::from_str(
3391 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3392 )
3393 .unwrap();
3394 assert_eq!(
3395 stamped,
3396 StderrTailEntry::Line {
3397 text: "boom".to_string(),
3398 truncated: true,
3399 at_ms: Some(1_789_801_440_685),
3400 }
3401 );
3402 let unstamped: StderrTailEntry =
3403 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3404 assert_eq!(
3405 unstamped,
3406 StderrTailEntry::Line {
3407 text: "boom".to_string(),
3408 truncated: false,
3409 at_ms: None,
3410 }
3411 );
3412 assert_eq!(
3415 serde_json::to_string(&unstamped).unwrap(),
3416 r#"{"kind":"line","text":"boom"}"#
3417 );
3418 assert_eq!(
3419 serde_json::to_value(&stamped).unwrap()["at_ms"],
3420 serde_json::json!(1_789_801_440_685u64)
3421 );
3422 }
3423
3424 #[test]
3425 fn tagged_unknown_values_round_trip_the_original_json() {
3426 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3427 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3428 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3429 }
3430
3431 #[test]
3432 fn tagged_unknown_values_round_trip_trailing_tag() {
3433 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
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#"{"reason":"because","state":"future_state"}"#;
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_middle_tag() {
3444 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
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":1,"state":"future_state","b":2}"#;
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_round_trip_deep_payload() {
3455 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3456 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3457 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3458
3459 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3460 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3461 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3462 }
3463
3464 #[test]
3465 fn tagged_unknown_values_reject_non_object_bodies() {
3466 for wire in ["42", r#""future""#, "[]"] {
3467 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3468 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3469 }
3470 }
3471
3472 #[test]
3473 fn duplicate_discriminators_reject_without_panicking() {
3474 assert_eq!(
3475 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3476 .unwrap(),
3477 ModuleDeclaredProvenance::Unverifiable
3478 );
3479 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3480 .unwrap()
3481 {
3482 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3483 _ => panic!("future discriminator decoded as a known variant"),
3484 }
3485
3486 let wires = [
3487 r#"{"status":"reported","status":"unverifiable"}"#,
3488 r#"{"status":"unverifiable","status":"reported"}"#,
3489 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3490 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3491 ];
3492
3493 for wire in wires {
3494 let result =
3495 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3496 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3497 assert!(
3498 result.unwrap().is_err(),
3499 "duplicate discriminator decoded: {wire}"
3500 );
3501 }
3502
3503 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3504 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3505 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3506 assert!(
3507 result.unwrap().is_err(),
3508 "duplicate discriminator decoded: {wire}"
3509 );
3510 }
3511
3512 #[test]
3513 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3514 let known_wire =
3515 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3516 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3517 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3518
3519 for wire in [
3520 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3521 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3522 ] {
3523 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3524 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3525 }
3526
3527 for wire in [
3528 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3529 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3530 ] {
3531 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3532 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3533 }
3534
3535 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3536 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3537 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3538
3539 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3540 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3541 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3542 }
3543
3544 #[test]
3545 fn tagged_unknown_member_does_not_discard_known_siblings() {
3546 let body = serde_json::json!({
3547 "modules": [{
3548 "module_id": "target",
3549 "routes": [
3550 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3551 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3552 ]
3553 }]
3554 });
3555 let decoded: ClientControlResponse = serde_json::from_value(
3556 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3557 )
3558 .unwrap();
3559 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3560 panic!("decoded wrong response variant");
3561 };
3562 assert_eq!(modules[0].routes.len(), 2);
3563 assert_eq!(
3564 modules[0].routes[1].consumer,
3565 SupervisorRouteConsumer::Direct { connection_id: 7 }
3566 );
3567 }
3568}
3569
3570#[cfg(test)]
3571mod launch_nonce_redaction_tests {
3572 use super::*;
3573
3574 const NONCE: &str = "nonce-f00dfeed1234abcd";
3575
3576 fn identity() -> ConsumerIdentity {
3577 ConsumerIdentity {
3578 module_id: "wernicke".to_string(),
3579 launch_nonce: NONCE.to_string(),
3580 }
3581 }
3582
3583 #[test]
3584 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3585 let printed = format!("{:?}", identity());
3586 assert!(printed.contains("wernicke"), "{printed}");
3587 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3588 }
3589
3590 #[test]
3591 fn route_open_request_debug_never_prints_the_nonce() {
3592 let request = ClientControlRequest::RouteOpen {
3593 busy_refusals: None,
3594 target: subc_protocol::RouteTarget::ToolProvider {
3595 module_id: "broca".to_string(),
3596 },
3597 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
3598 consumer_identity: Some(identity()),
3599 consumer_capabilities: None,
3600 role_versions: None,
3601 admission_facts: None,
3602 scope: None,
3603 };
3604 let printed = format!("{request:?}");
3605 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3606 }
3607}