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
88#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
90pub struct ConsumerIdentity {
91 pub module_id: String,
92 pub launch_nonce: String,
93}
94
95impl std::fmt::Debug for ConsumerIdentity {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 f.debug_struct("ConsumerIdentity")
102 .field("module_id", &self.module_id)
103 .field(
104 "launch_nonce",
105 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
106 )
107 .finish()
108 }
109}
110
111pub mod ops {
122 pub const SERVER: &str = "server.";
123 pub const CATALOG: &str = "catalog.";
124 pub const ROUTE: &str = "route.";
125 pub const SUPERVISOR: &str = "supervisor.";
126 pub const CONFIG: &str = "config.";
127
128 pub const SERVER_DESCRIBE: &str = "server.describe";
129 pub const CATALOG_LIST: &str = "catalog.list";
130 pub const ROUTE_OPEN: &str = "route.open";
131 pub const ROUTE_POLL: &str = "route.poll";
132 pub const ROUTE_CLOSING: &str = "route.closing";
133 pub const ROUTE_CLOSED: &str = "route.closed";
134 pub const SUPERVISOR_LIST: &str = "supervisor.list";
135 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
136 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
137 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
138 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
139 pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
140 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
141 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
142 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
143 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
144 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
145 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
146 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
147 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
148 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
149 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
150 pub const ACTIVITY_RECORD: &str = "activity.record";
151 pub const ACTIVITY_QUERY: &str = "activity.query";
152 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
153 pub const APP_OPEN: &str = "app.open";
154}
155
156#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
158#[serde(tag = "op")]
159#[allow(clippy::large_enum_variant)]
162pub enum ClientControlRequest {
163 #[serde(rename = "server.describe")]
164 ServerDescribe {},
165 #[serde(rename = "catalog.list")]
166 CatalogList {
167 #[serde(default)]
172 module_id: Option<String>,
173 },
174 #[serde(rename = "route.open")]
175 RouteOpen {
176 target: RouteTarget,
177 identity: BindIdentity,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
187 consumer_identity: Option<ConsumerIdentity>,
188 #[serde(default, skip_serializing_if = "Option::is_none")]
196 consumer_capabilities: Option<Vec<String>>,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
208 role_versions: Option<BTreeMap<String, String>>,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
211 admission_facts: Option<serde_json::Value>,
212 #[serde(default, skip_serializing_if = "Option::is_none")]
219 scope: Option<ScopeSelector>,
220 },
221 #[serde(rename = "route.poll")]
222 RoutePoll {
223 route_channel: u16,
224 route_epoch: u32,
225 kind: PollKind,
226 },
227 #[serde(rename = "supervisor.list")]
228 SupervisorList {},
229 #[serde(rename = "supervisor.spawn_snapshot")]
231 SupervisorSpawnSnapshot {},
232 #[serde(rename = "supervisor.spawn_subscribe")]
248 SupervisorSpawnSubscribe {
249 #[serde(default, skip_serializing_if = "Option::is_none")]
250 since: Option<SpawnCursor>,
251 },
252 #[serde(rename = "supervisor.restart")]
253 SupervisorRestart {
254 module_id: String,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
265 drain_timeout_ms: Option<u64>,
266 },
267 #[serde(rename = "supervisor.swap")]
282 SupervisorSwap {
283 module_id: String,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
287 ready_timeout_ms: Option<u64>,
288 },
289 #[serde(rename = "supervisor.reload")]
290 SupervisorReload { module_id: String },
291 #[serde(rename = "supervisor.rescan")]
292 SupervisorRescan {
293 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
313 preview: bool,
314 },
315 #[serde(rename = "supervisor.rescan_checked")]
339 SupervisorRescanChecked {
340 preview: bool,
341 #[serde(default, skip_serializing_if = "Option::is_none")]
342 candidate: Option<String>,
343 #[serde(default, skip_serializing_if = "Option::is_none")]
344 expect: Option<RescanExpect>,
345 },
346 #[serde(rename = "supervisor.release_reserved")]
350 SupervisorReleaseReserved { module_id: String },
351 #[serde(rename = "supervisor.set_enabled")]
352 SupervisorSetEnabled { module_id: String, enabled: bool },
353 #[serde(rename = "supervisor.health_probe")]
354 SupervisorHealthProbe { module_id: String },
355 #[serde(rename = "supervisor.health")]
356 SupervisorHealth {},
357 #[serde(rename = "supervisor.routes")]
370 SupervisorRoutes {
371 #[serde(default, skip_serializing_if = "Option::is_none")]
372 module_id: Option<String>,
373 },
374 #[serde(rename = "supervisor.provenance")]
377 SupervisorProvenance {
378 #[serde(default, skip_serializing_if = "Option::is_none")]
379 module_id: Option<String>,
380 },
381 #[serde(rename = "supervisor.stderr_tail")]
389 SupervisorStderrTail {
390 module_id: String,
391 #[serde(default, skip_serializing_if = "Option::is_none")]
392 max_lines: Option<u32>,
393 #[serde(default, skip_serializing_if = "Option::is_none")]
394 max_bytes: Option<u32>,
395 },
396 #[serde(rename = "supervisor.terminals")]
409 SupervisorTerminals { module_id: String },
410}
411
412#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
414#[serde(tag = "op")]
415pub enum ClientControlResponse {
416 #[serde(rename = "server.describe")]
417 ServerDescribe {
418 protocol_ver: u8,
419 subc_ops: Vec<String>,
420 capabilities: Vec<String>,
421 connected_clients: u64,
422 #[serde(default, skip_serializing_if = "Option::is_none")]
423 counters: Option<serde_json::Value>,
424 #[serde(default, skip_serializing_if = "Option::is_none")]
431 build_git_sha: Option<String>,
432 #[serde(default, skip_serializing_if = "Option::is_none")]
438 build_lock_digest: Option<String>,
439 #[serde(default, skip_serializing_if = "Vec::is_empty")]
443 capability_requirements: Vec<CapabilityRequirementStatus>,
444 #[serde(default, skip_serializing_if = "Option::is_none")]
449 machine_id: Option<String>,
450 #[serde(default, skip_serializing_if = "Option::is_none")]
459 config_path: Option<PathBuf>,
460 },
461 #[serde(rename = "catalog.list")]
462 CatalogList {
463 generation: u64,
464 modules: Vec<CatalogEntry>,
465 subc_ops: Vec<String>,
466 },
467 #[serde(rename = "route.open")]
468 RouteOpen {
469 route_channel: u16,
470 route_epoch: u32,
471 },
472 #[serde(rename = "route.poll")]
473 RoutePoll {
474 route_channel: u16,
475 route_epoch: u32,
476 status: Option<String>,
477 live: Option<bool>,
478 },
479 #[serde(rename = "supervisor.list")]
480 SupervisorList {
481 generation: u64,
482 modules: Vec<SupervisorEntry>,
483 },
484 #[serde(rename = "supervisor.spawn_snapshot")]
485 SupervisorSpawnSnapshot {
486 #[serde(flatten)]
487 snapshot: SpawnSnapshot,
488 },
489 #[serde(rename = "supervisor.ack")]
490 SupervisorAck { module_id: String, applied: bool },
491 #[serde(rename = "supervisor.rescan")]
492 SupervisorRescan {
493 #[serde(flatten)]
494 result: SupervisorRescanResult,
495 },
496 #[serde(rename = "supervisor.health_probe")]
497 SupervisorHealthProbe {
498 module_id: String,
499 status: HealthStatus,
500 #[serde(default, skip_serializing_if = "Option::is_none")]
501 detail: Option<String>,
502 #[serde(default, skip_serializing_if = "Option::is_none")]
503 metrics: Option<serde_json::Value>,
504 },
505 #[serde(rename = "supervisor.health")]
506 SupervisorHealth {
507 generation: u64,
508 modules: Vec<SupervisorHealthEntry>,
509 },
510 #[serde(rename = "supervisor.routes")]
511 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
512 #[serde(rename = "supervisor.provenance")]
513 SupervisorProvenance {
514 daemon: SupervisorDaemonProvenance,
515 modules: Vec<SupervisorModuleProvenance>,
516 },
517 #[serde(rename = "supervisor.stderr_tail")]
518 SupervisorStderrTail {
519 module_id: String,
520 #[serde(flatten)]
521 tail: StderrTail,
522 },
523 #[serde(rename = "supervisor.terminals")]
524 SupervisorTerminals {
525 module_id: String,
526 #[serde(flatten)]
527 terminals: TerminalHistory,
528 },
529}
530
531#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
536#[serde(tag = "op")]
537pub enum ClientControlPush {
538 #[serde(rename = "route.closing")]
539 RouteClosing {
540 module_id: String,
541 #[serde(default)]
544 channels: Vec<u16>,
545 reason: RouteCloseReason,
546 },
547 #[serde(rename = "route.closed")]
548 RouteClosed {
549 module_id: String,
550 #[serde(default)]
553 channels: Vec<u16>,
554 reason: RouteCloseReason,
555 drained: bool,
557 abandoned: u32,
560 #[serde(default)]
562 excluded_subscriptions: u32,
563 #[serde(default, skip_serializing_if = "Option::is_none")]
569 terminal: Option<bool>,
570 },
571}
572
573#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
575pub struct SpawnCursor {
576 pub daemon_incarnation: String,
577 pub seq: u64,
578}
579
580#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
582pub struct LiveSpawn {
583 pub module_id: String,
584 pub spawn_generation: u64,
585 pub pid: u32,
586 pub spawned_at_ms: u64,
587}
588
589#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
591pub struct SpawnSnapshot {
592 pub cursor: SpawnCursor,
593 pub ring_bound: u64,
595 pub live: Vec<LiveSpawn>,
596}
597
598#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
600#[serde(rename_all = "snake_case")]
601pub enum SpawnEventKind {
602 Spawned,
603 Exited,
604}
605
606#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
612pub struct SpawnEvent {
613 pub cursor: SpawnCursor,
614 pub kind: SpawnEventKind,
615 pub module_id: String,
616 pub spawn_generation: u64,
617 pub pid: u32,
618 #[serde(default, skip_serializing_if = "Option::is_none")]
619 pub exit_code: Option<i32>,
620 #[serde(default, skip_serializing_if = "Option::is_none")]
621 pub exit_signal: Option<i32>,
622}
623
624#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
626pub struct StderrTail {
627 pub capture: StderrCaptureState,
628 pub entries: Vec<StderrTailEntry>,
629 #[serde(default, skip_serializing_if = "is_zero_u64")]
638 pub dropped_lines: u64,
639}
640
641#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
643pub struct SupervisorRouteModule {
644 pub module_id: String,
645 pub routes: Vec<SupervisorRoute>,
646}
647
648#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
650pub struct SupervisorRoute {
651 pub consumer: SupervisorRouteConsumer,
652 pub age_ms: u64,
654 pub draining: bool,
657 #[serde(default, skip_serializing_if = "Option::is_none")]
663 pub drain_reason: Option<RouteCloseReason>,
664}
665
666#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
668pub struct SupervisorModuleProvenance {
669 pub module_id: String,
670 pub module_declared: ModuleDeclaredProvenance,
671 pub daemon_observed: SupervisorObservedProcess,
672}
673
674#[derive(Debug, Clone, PartialEq)]
676pub enum ModuleDeclaredProvenance {
677 Reported {
678 build: ManifestProvenance,
679 },
680 Unverifiable,
681 Unknown {
684 tag: String,
685 body: OrderedJsonObject,
686 },
687}
688
689#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
694pub struct SupervisorObservedProcess {
695 #[serde(default, skip_serializing_if = "Option::is_none")]
701 pub launch_nonce_source: Option<String>,
702 #[serde(default, skip_serializing_if = "Option::is_none")]
703 pub pid: Option<u32>,
704 #[serde(default, skip_serializing_if = "Option::is_none")]
705 pub spawned_at_ms: Option<u64>,
706 #[serde(default, skip_serializing_if = "Option::is_none")]
707 pub spawned_from: Option<PathBuf>,
708 pub running_image: RunningImageAgreement,
709}
710
711#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
714pub struct PendingReloadVerdict {
715 pub path: ReloadPathAgreement,
716 pub image: RunningImageAgreement,
717 #[serde(default, skip_serializing_if = "Option::is_none")]
718 pub spec: Option<LaunchSpecAgreement>,
719}
720
721#[cfg(test)]
722mod launch_spec_wire_tests {
723 use super::*;
724
725 #[test]
726 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
727 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
728 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
729 assert_eq!(parsed.spec, None);
730 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
731 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
732 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
733 assert!(
734 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
735 );
736 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
737 let unavailable = LaunchSpecAgreement::Unavailable {
738 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
739 };
740 let encoded = serde_json::to_string(&unavailable).unwrap();
741 assert_eq!(
742 encoded,
743 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
744 );
745 assert_eq!(
746 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
747 unavailable
748 );
749 }
750}
751
752#[derive(Debug, Clone, PartialEq)]
755pub enum LaunchSpecAgreement {
756 Match,
757 Mismatch,
758 Unavailable {
759 reason: LaunchSpecUnavailableReason,
760 },
761 Unknown {
762 tag: String,
763 body: OrderedJsonObject,
764 },
765}
766
767open_string_enum! {
768 LaunchSpecUnavailableReason {
769 NotRunning => "not_running",
770 SpawnedSpecUnavailable => "spawned_spec_unavailable",
771 }
772}
773
774#[derive(Debug, Clone, PartialEq)]
776pub enum ReloadPathAgreement {
777 Match,
778 Mismatch {
779 configured: PathBuf,
780 spawned_from: PathBuf,
781 },
782 Unavailable {
783 reason: ReloadPathUnavailableReason,
784 },
785 Unknown {
786 tag: String,
787 body: OrderedJsonObject,
788 },
789}
790
791open_string_enum! {
792 ReloadPathUnavailableReason {
794 NotRunning => "not_running",
795 SpawnedPathUnavailable => "spawned_path_unavailable",
796 }
797}
798
799#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
801pub struct SupervisorDaemonProvenance {
802 pub daemon_build: DaemonBuildProvenance,
803 pub daemon_observed: DaemonObservedProcess,
804}
805
806#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
808pub struct DaemonBuildProvenance {
809 #[serde(default, skip_serializing_if = "Option::is_none")]
810 pub build_git_sha: Option<String>,
811 #[serde(default, skip_serializing_if = "Option::is_none")]
812 pub build_lock_digest: Option<String>,
813}
814
815#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
817pub struct DaemonObservedProcess {
818 #[serde(default, skip_serializing_if = "Option::is_none")]
819 pub pid: Option<u32>,
820 #[serde(default, skip_serializing_if = "Option::is_none")]
825 pub started_at_ms: Option<u64>,
826 pub running_image: RunningImageAgreement,
827}
828
829#[derive(Debug, Clone, PartialEq)]
831pub enum RunningImageAgreement {
832 Match {
833 evidence: RunningImageEvidence,
834 },
835 Mismatch {
836 running: RunningImageEvidence,
837 disk: RunningImageEvidence,
838 },
839 Unavailable {
840 reason: RunningImageUnavailableReason,
841 },
842 Unknown {
845 tag: String,
846 body: OrderedJsonObject,
847 },
848}
849
850#[derive(Debug, Clone, PartialEq)]
852pub enum RunningImageEvidence {
853 LinuxProcSha256 {
854 digest: String,
855 },
856 MacosSpawnInode {
857 device: u64,
858 inode: u64,
859 },
860 WindowsSpawnFileId {
862 volume_serial_number: u64,
863 file_id: [u8; 16],
864 },
865 Unknown {
868 tag: String,
869 body: OrderedJsonObject,
870 },
871}
872
873open_string_enum! {
874 RunningImageUnavailableReason {
876 NotRunning => "not_running",
877 UnsupportedPlatform => "unsupported_platform",
878 RunningExecutableUnreadable => "running_executable_unreadable",
879 RunningExecutablePermissionDenied => "running_executable_permission_denied",
880 ProcessHidden => "process_hidden",
881 SpawnedPathUnreadable => "spawned_path_unreadable",
882 HashFailed => "hash_failed",
883 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
884 }
885}
886
887#[derive(Debug, Clone, PartialEq)]
893pub enum SupervisorRouteConsumer {
894 Reserved {
895 module_id: String,
896 },
897 Direct {
898 connection_id: u64,
899 },
900 Unknown {
903 tag: String,
904 body: OrderedJsonObject,
905 },
906}
907
908#[derive(Debug, Clone, PartialEq)]
915pub enum StderrCaptureState {
916 Captured,
919 Incomplete { reason: String },
921 NotCaptured { reason: String },
923 Unknown {
926 tag: String,
927 body: OrderedJsonObject,
928 },
929}
930
931#[derive(Debug, Clone, PartialEq)]
932pub enum StderrTailEntry {
933 Line {
934 text: String,
935 truncated: bool,
940 at_ms: Option<u64>,
944 },
945 ProcessStart,
950 Unknown {
953 tag: String,
954 body: OrderedJsonObject,
955 },
956}
957
958#[derive(Debug, Serialize, Deserialize)]
959#[serde(tag = "status", rename_all = "snake_case")]
960enum ModuleDeclaredProvenanceWire {
961 Reported { build: ManifestProvenance },
962 Unverifiable,
963}
964
965#[derive(Debug, Serialize, Deserialize)]
966#[serde(tag = "status", rename_all = "snake_case")]
967enum RunningImageAgreementWire {
968 Match {
969 evidence: RunningImageEvidence,
970 },
971 Mismatch {
972 running: RunningImageEvidence,
973 disk: RunningImageEvidence,
974 },
975 Unavailable {
976 reason: RunningImageUnavailableReason,
977 },
978}
979
980#[derive(Debug, Serialize, Deserialize)]
981#[serde(tag = "status", rename_all = "snake_case")]
982enum ReloadPathAgreementWire {
983 Match,
984 Mismatch {
985 configured: PathBuf,
986 spawned_from: PathBuf,
987 },
988 Unavailable {
989 reason: ReloadPathUnavailableReason,
990 },
991}
992
993#[derive(Debug, Serialize, Deserialize)]
994#[serde(tag = "status", rename_all = "snake_case")]
995enum LaunchSpecAgreementWire {
996 Match,
997 Mismatch,
998 Unavailable { reason: LaunchSpecUnavailableReason },
999}
1000
1001#[derive(Debug, Serialize, Deserialize)]
1002#[serde(tag = "method", rename_all = "snake_case")]
1003enum RunningImageEvidenceWire {
1004 LinuxProcSha256 {
1005 digest: String,
1006 },
1007 MacosSpawnInode {
1008 device: u64,
1009 inode: u64,
1010 },
1011 WindowsSpawnFileId {
1012 volume_serial_number: u64,
1013 file_id: [u8; 16],
1014 },
1015}
1016
1017#[derive(Debug, Serialize, Deserialize)]
1018#[serde(tag = "kind", rename_all = "snake_case")]
1019enum SupervisorRouteConsumerWire {
1020 Reserved { module_id: String },
1021 Direct { connection_id: u64 },
1022}
1023
1024#[derive(Debug, Serialize, Deserialize)]
1025#[serde(tag = "state", rename_all = "snake_case")]
1026enum StderrCaptureStateWire {
1027 Captured,
1028 Incomplete { reason: String },
1029 NotCaptured { reason: String },
1030}
1031
1032#[derive(Debug, Serialize, Deserialize)]
1033#[serde(tag = "status", rename_all = "snake_case")]
1034enum ChildResourceUsageWire {
1035 Measured(ChildResourceReading),
1036 Unavailable {
1037 reason: ChildResourceUnavailableReason,
1038 },
1039}
1040
1041#[derive(Debug, Serialize, Deserialize)]
1042#[serde(tag = "kind", rename_all = "snake_case")]
1043enum StderrTailEntryWire {
1044 Line {
1045 text: String,
1046 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1047 truncated: bool,
1048 #[serde(default, skip_serializing_if = "Option::is_none")]
1051 at_ms: Option<u64>,
1052 },
1053 ProcessStart,
1054}
1055
1056#[derive(Debug, Clone, PartialEq)]
1058pub enum OrderedJsonValue {
1059 Null,
1060 Bool(bool),
1061 Number(serde_json::Number),
1062 String(String),
1063 Array(Vec<Self>),
1064 Object(OrderedJsonObject),
1065}
1066
1067#[derive(Debug, Clone, PartialEq)]
1069pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1070
1071impl OrderedJsonObject {
1072 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1074 &self.0
1075 }
1076
1077 fn into_value(self) -> serde_json::Value {
1078 serde_json::Value::Object(
1079 self.0
1080 .into_iter()
1081 .map(|(key, value)| (key, value.into_value()))
1082 .collect(),
1083 )
1084 }
1085}
1086
1087impl OrderedJsonValue {
1088 fn into_value(self) -> serde_json::Value {
1089 match self {
1090 Self::Null => serde_json::Value::Null,
1091 Self::Bool(value) => serde_json::Value::Bool(value),
1092 Self::Number(value) => serde_json::Value::Number(value),
1093 Self::String(value) => serde_json::Value::String(value),
1094 Self::Array(values) => {
1095 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1096 }
1097 Self::Object(value) => value.into_value(),
1098 }
1099 }
1100}
1101
1102impl Serialize for OrderedJsonValue {
1103 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1104 where
1105 S: Serializer,
1106 {
1107 match self {
1108 Self::Null => serializer.serialize_unit(),
1109 Self::Bool(value) => serializer.serialize_bool(*value),
1110 Self::Number(value) => value.serialize(serializer),
1111 Self::String(value) => serializer.serialize_str(value),
1112 Self::Array(values) => values.serialize(serializer),
1113 Self::Object(value) => value.serialize(serializer),
1114 }
1115 }
1116}
1117
1118impl<'de> Deserialize<'de> for OrderedJsonValue {
1119 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1120 where
1121 D: Deserializer<'de>,
1122 {
1123 struct OrderedValueVisitor;
1124
1125 impl<'de> Visitor<'de> for OrderedValueVisitor {
1126 type Value = OrderedJsonValue;
1127
1128 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1129 formatter.write_str("a JSON value with ordered object members")
1130 }
1131
1132 fn visit_unit<E>(self) -> Result<Self::Value, E>
1133 where
1134 E: serde::de::Error,
1135 {
1136 Ok(OrderedJsonValue::Null)
1137 }
1138
1139 fn visit_none<E>(self) -> Result<Self::Value, E>
1140 where
1141 E: serde::de::Error,
1142 {
1143 Ok(OrderedJsonValue::Null)
1144 }
1145
1146 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1147 where
1148 D: Deserializer<'de>,
1149 {
1150 OrderedJsonValue::deserialize(deserializer)
1151 }
1152
1153 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1154 where
1155 E: serde::de::Error,
1156 {
1157 Ok(OrderedJsonValue::Bool(value))
1158 }
1159
1160 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1161 where
1162 E: serde::de::Error,
1163 {
1164 Ok(OrderedJsonValue::Number(value.into()))
1165 }
1166
1167 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1168 where
1169 E: serde::de::Error,
1170 {
1171 Ok(OrderedJsonValue::Number(value.into()))
1172 }
1173
1174 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1175 where
1176 E: serde::de::Error,
1177 {
1178 serde_json::Number::from_f64(value)
1179 .map(OrderedJsonValue::Number)
1180 .ok_or_else(|| E::custom("non-finite JSON number"))
1181 }
1182
1183 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1184 where
1185 E: serde::de::Error,
1186 {
1187 Ok(OrderedJsonValue::String(value.to_owned()))
1188 }
1189
1190 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1191 where
1192 E: serde::de::Error,
1193 {
1194 Ok(OrderedJsonValue::String(value))
1195 }
1196
1197 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1198 where
1199 A: SeqAccess<'de>,
1200 {
1201 let mut values = Vec::new();
1202 while let Some(value) = sequence.next_element()? {
1203 values.push(value);
1204 }
1205 Ok(OrderedJsonValue::Array(values))
1206 }
1207
1208 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1209 where
1210 A: MapAccess<'de>,
1211 {
1212 let mut entries = Vec::new();
1213 while let Some((key, value)) = map.next_entry()? {
1214 entries.push((key, value));
1215 }
1216 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1217 }
1218 }
1219
1220 deserializer.deserialize_any(OrderedValueVisitor)
1221 }
1222}
1223
1224impl Serialize for OrderedJsonObject {
1225 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1226 where
1227 S: Serializer,
1228 {
1229 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1230 for (key, value) in &self.0 {
1231 map.serialize_entry(key, value)?;
1232 }
1233 map.end()
1234 }
1235}
1236
1237impl<'de> Deserialize<'de> for OrderedJsonObject {
1238 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1239 where
1240 D: Deserializer<'de>,
1241 {
1242 struct OrderedObjectVisitor;
1243
1244 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1245 type Value = OrderedJsonObject;
1246
1247 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1248 formatter.write_str("an object with ordered JSON members")
1249 }
1250
1251 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1252 where
1253 A: MapAccess<'de>,
1254 {
1255 let mut entries = Vec::new();
1256 while let Some((key, value)) = map.next_entry()? {
1257 entries.push((key, value));
1258 }
1259 Ok(OrderedJsonObject(entries))
1260 }
1261 }
1262
1263 deserializer.deserialize_map(OrderedObjectVisitor)
1264 }
1265}
1266
1267fn read_tagged<'de, D>(
1268 deserializer: D,
1269 field: &'static str,
1270) -> Result<(String, OrderedJsonObject), D::Error>
1271where
1272 D: Deserializer<'de>,
1273{
1274 let body = OrderedJsonObject::deserialize(deserializer)?;
1275 let mut tag = None;
1276 for (key, value) in body.as_entries() {
1277 if key != field {
1278 continue;
1279 }
1280 if tag.is_some() {
1281 return Err(D::Error::custom(format!(
1282 "tagged object has duplicate `{field}` field"
1283 )));
1284 }
1285 let OrderedJsonValue::String(value) = value else {
1286 return Err(D::Error::custom(format!(
1287 "tagged object has no string `{field}` field"
1288 )));
1289 };
1290 tag = Some(value);
1291 }
1292 let Some(tag) = tag else {
1293 return Err(D::Error::custom(format!(
1294 "tagged object has no string `{field}` field"
1295 )));
1296 };
1297 Ok((tag.to_string(), body))
1298}
1299
1300fn read_ordered_tagged(
1301 value: OrderedJsonValue,
1302 field: &'static str,
1303) -> Result<(String, OrderedJsonObject), String> {
1304 let OrderedJsonValue::Object(body) = value else {
1305 return Err(format!("expected tagged object with `{field}` field"));
1306 };
1307 let mut tag = None;
1308 for (key, value) in body.as_entries() {
1309 if key != field {
1310 continue;
1311 }
1312 if tag.is_some() {
1313 return Err(format!("tagged object has duplicate `{field}` field"));
1314 }
1315 let OrderedJsonValue::String(value) = value else {
1316 return Err(format!("tagged object has no string `{field}` field"));
1317 };
1318 tag = Some(value);
1319 }
1320 let Some(tag) = tag else {
1321 return Err(format!("tagged object has no string `{field}` field"));
1322 };
1323 Ok((tag.to_string(), body))
1324}
1325
1326fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1327 body.as_entries()
1328 .iter()
1329 .find_map(|(key, value)| (key == field).then_some(value))
1330}
1331
1332fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1333 match ordered_field(body, field) {
1334 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1335 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1336 None => Err(format!("tagged object has no `{field}` field")),
1337 }
1338}
1339
1340fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1341 let (tag, body) = read_ordered_tagged(value, "method")?;
1342 match tag.as_str() {
1343 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1344 digest: ordered_string(&body, "digest")?,
1345 }),
1346 "macos_spawn_inode" => {
1347 let device = ordered_field(&body, "device")
1348 .and_then(|value| match value {
1349 OrderedJsonValue::Number(number) => number.as_u64(),
1350 _ => None,
1351 })
1352 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1353 let inode = ordered_field(&body, "inode")
1354 .and_then(|value| match value {
1355 OrderedJsonValue::Number(number) => number.as_u64(),
1356 _ => None,
1357 })
1358 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1359 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1360 }
1361 "windows_spawn_file_id" => {
1362 let wire: RunningImageEvidenceWire = serde_json::from_value(
1363 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1364 )
1365 .map_err(|error| error.to_string())?;
1366 match wire {
1367 RunningImageEvidenceWire::WindowsSpawnFileId {
1368 volume_serial_number,
1369 file_id,
1370 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1371 volume_serial_number,
1372 file_id,
1373 }),
1374 _ => unreachable!(),
1375 }
1376 }
1377 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1378 }
1379}
1380
1381impl Serialize for ModuleDeclaredProvenance {
1382 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1383 where
1384 S: Serializer,
1385 {
1386 match self {
1387 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1388 build: build.clone(),
1389 }
1390 .serialize(serializer),
1391 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1392 Self::Unknown { body, .. } => body.serialize(serializer),
1393 }
1394 }
1395}
1396
1397impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1398 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1399 where
1400 D: serde::Deserializer<'de>,
1401 {
1402 let (tag, value) = read_tagged(deserializer, "status")?;
1403 match tag.as_str() {
1404 "reported" => match serde_json::from_value(value.into_value())
1405 .map_err(D::Error::custom)?
1406 {
1407 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1408 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1409 },
1410 "unverifiable" => {
1411 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1412 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1413 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1414 }
1415 }
1416 _ => Ok(Self::Unknown { tag, body: value }),
1417 }
1418 }
1419}
1420
1421impl Serialize for RunningImageAgreement {
1422 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1423 where
1424 S: Serializer,
1425 {
1426 match self {
1427 Self::Match { evidence } => RunningImageAgreementWire::Match {
1428 evidence: evidence.clone(),
1429 }
1430 .serialize(serializer),
1431 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1432 running: running.clone(),
1433 disk: disk.clone(),
1434 }
1435 .serialize(serializer),
1436 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1437 reason: reason.clone(),
1438 }
1439 .serialize(serializer),
1440 Self::Unknown { body, .. } => body.serialize(serializer),
1441 }
1442 }
1443}
1444
1445impl Serialize for ReloadPathAgreement {
1446 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1447 where
1448 S: Serializer,
1449 {
1450 match self {
1451 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1452 Self::Mismatch {
1453 configured,
1454 spawned_from,
1455 } => ReloadPathAgreementWire::Mismatch {
1456 configured: configured.clone(),
1457 spawned_from: spawned_from.clone(),
1458 }
1459 .serialize(serializer),
1460 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1461 reason: reason.clone(),
1462 }
1463 .serialize(serializer),
1464 Self::Unknown { body, .. } => body.serialize(serializer),
1465 }
1466 }
1467}
1468
1469impl Serialize for LaunchSpecAgreement {
1470 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1471 where
1472 S: Serializer,
1473 {
1474 match self {
1475 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1476 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1477 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1478 reason: reason.clone(),
1479 }
1480 .serialize(serializer),
1481 Self::Unknown { body, .. } => body.serialize(serializer),
1482 }
1483 }
1484}
1485
1486impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1487 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1488 where
1489 D: Deserializer<'de>,
1490 {
1491 let (tag, body) = read_tagged(deserializer, "status")?;
1492 match tag.as_str() {
1493 "match" => Ok(Self::Match),
1494 "mismatch" => Ok(Self::Mismatch),
1495 "unavailable" => match serde_json::from_value(body.into_value())
1496 .map_err(D::Error::custom)?
1497 {
1498 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1499 _ => unreachable!(),
1500 },
1501 _ => Ok(Self::Unknown { tag, body }),
1502 }
1503 }
1504}
1505
1506impl<'de> Deserialize<'de> for ReloadPathAgreement {
1507 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1508 where
1509 D: Deserializer<'de>,
1510 {
1511 let (tag, body) = read_tagged(deserializer, "status")?;
1512 match tag.as_str() {
1513 "match" => Ok(Self::Match),
1514 "mismatch" => {
1515 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1516 ReloadPathAgreementWire::Mismatch {
1517 configured,
1518 spawned_from,
1519 } => Ok(Self::Mismatch {
1520 configured,
1521 spawned_from,
1522 }),
1523 _ => unreachable!(),
1524 }
1525 }
1526 "unavailable" => match serde_json::from_value(body.into_value())
1527 .map_err(D::Error::custom)?
1528 {
1529 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1530 _ => unreachable!(),
1531 },
1532 _ => Ok(Self::Unknown { tag, body }),
1533 }
1534 }
1535}
1536
1537impl<'de> Deserialize<'de> for RunningImageAgreement {
1538 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1539 where
1540 D: serde::Deserializer<'de>,
1541 {
1542 let (tag, value) = read_tagged(deserializer, "status")?;
1543 match tag.as_str() {
1544 "match" => Ok(Self::Match {
1545 evidence: decode_running_image_evidence(
1546 ordered_field(&value, "evidence")
1547 .cloned()
1548 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1549 )
1550 .map_err(D::Error::custom)?,
1551 }),
1552 "mismatch" => Ok(Self::Mismatch {
1553 running: decode_running_image_evidence(
1554 ordered_field(&value, "running")
1555 .cloned()
1556 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1557 )
1558 .map_err(D::Error::custom)?,
1559 disk: decode_running_image_evidence(
1560 ordered_field(&value, "disk")
1561 .cloned()
1562 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1563 )
1564 .map_err(D::Error::custom)?,
1565 }),
1566 "unavailable" => Ok(Self::Unavailable {
1567 reason: serde_json::from_value(
1568 ordered_field(&value, "reason")
1569 .cloned()
1570 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1571 .into_value(),
1572 )
1573 .map_err(D::Error::custom)?,
1574 }),
1575 _ => Ok(Self::Unknown { tag, body: value }),
1576 }
1577 }
1578}
1579
1580impl Serialize for ChildResourceUsage {
1581 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1582 where
1583 S: Serializer,
1584 {
1585 match self {
1586 Self::Measured(reading) => {
1587 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1588 }
1589 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1590 reason: reason.clone(),
1591 }
1592 .serialize(serializer),
1593 Self::Unknown { body, .. } => body.serialize(serializer),
1594 }
1595 }
1596}
1597
1598impl<'de> Deserialize<'de> for ChildResourceUsage {
1599 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1600 where
1601 D: Deserializer<'de>,
1602 {
1603 let (tag, body) = read_tagged(deserializer, "status")?;
1604 match tag.as_str() {
1605 "measured" | "unavailable" => {
1606 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1607 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1608 ChildResourceUsageWire::Unavailable { reason } => {
1609 Ok(Self::Unavailable { reason })
1610 }
1611 }
1612 }
1613 _ => Ok(Self::Unknown { tag, body }),
1614 }
1615 }
1616}
1617
1618impl Serialize for RunningImageEvidence {
1619 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1620 where
1621 S: Serializer,
1622 {
1623 match self {
1624 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1625 digest: digest.clone(),
1626 }
1627 .serialize(serializer),
1628 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1629 device: *device,
1630 inode: *inode,
1631 }
1632 .serialize(serializer),
1633 Self::WindowsSpawnFileId {
1634 volume_serial_number,
1635 file_id,
1636 } => RunningImageEvidenceWire::WindowsSpawnFileId {
1637 volume_serial_number: *volume_serial_number,
1638 file_id: *file_id,
1639 }
1640 .serialize(serializer),
1641 Self::Unknown { body, .. } => body.serialize(serializer),
1642 }
1643 }
1644}
1645
1646impl<'de> Deserialize<'de> for RunningImageEvidence {
1647 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1648 where
1649 D: serde::Deserializer<'de>,
1650 {
1651 let (tag, value) = read_tagged(deserializer, "method")?;
1652 match tag.as_str() {
1653 "linux_proc_sha256" => {
1654 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1655 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1656 Ok(Self::LinuxProcSha256 { digest })
1657 }
1658 _ => unreachable!(),
1659 }
1660 }
1661 "macos_spawn_inode" => {
1662 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1663 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1664 Ok(Self::MacosSpawnInode { device, inode })
1665 }
1666 _ => unreachable!(),
1667 }
1668 }
1669 "windows_spawn_file_id" => {
1670 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1671 RunningImageEvidenceWire::WindowsSpawnFileId {
1672 volume_serial_number,
1673 file_id,
1674 } => Ok(Self::WindowsSpawnFileId {
1675 volume_serial_number,
1676 file_id,
1677 }),
1678 _ => unreachable!(),
1679 }
1680 }
1681 _ => Ok(Self::Unknown { tag, body: value }),
1682 }
1683 }
1684}
1685
1686impl Serialize for SupervisorRouteConsumer {
1687 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1688 where
1689 S: Serializer,
1690 {
1691 match self {
1692 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1693 module_id: module_id.clone(),
1694 }
1695 .serialize(serializer),
1696 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1697 connection_id: *connection_id,
1698 }
1699 .serialize(serializer),
1700 Self::Unknown { body, .. } => body.serialize(serializer),
1701 }
1702 }
1703}
1704
1705impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1706 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1707 where
1708 D: serde::Deserializer<'de>,
1709 {
1710 let (tag, value) = read_tagged(deserializer, "kind")?;
1711 match tag.as_str() {
1712 "reserved" => {
1713 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1714 SupervisorRouteConsumerWire::Reserved { module_id } => {
1715 Ok(Self::Reserved { module_id })
1716 }
1717 _ => unreachable!(),
1718 }
1719 }
1720 "direct" => {
1721 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1722 SupervisorRouteConsumerWire::Direct { connection_id } => {
1723 Ok(Self::Direct { connection_id })
1724 }
1725 _ => unreachable!(),
1726 }
1727 }
1728 _ => Ok(Self::Unknown { tag, body: value }),
1729 }
1730 }
1731}
1732
1733impl Serialize for StderrCaptureState {
1734 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1735 where
1736 S: Serializer,
1737 {
1738 match self {
1739 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1740 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1741 reason: reason.clone(),
1742 }
1743 .serialize(serializer),
1744 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1745 reason: reason.clone(),
1746 }
1747 .serialize(serializer),
1748 Self::Unknown { body, .. } => body.serialize(serializer),
1749 }
1750 }
1751}
1752
1753impl<'de> Deserialize<'de> for StderrCaptureState {
1754 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1755 where
1756 D: serde::Deserializer<'de>,
1757 {
1758 let (tag, value) = read_tagged(deserializer, "state")?;
1759 match tag.as_str() {
1760 "captured" => {
1761 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1762 StderrCaptureStateWire::Captured => Ok(Self::Captured),
1763 _ => unreachable!(),
1764 }
1765 }
1766 "incomplete" => match serde_json::from_value(value.into_value())
1767 .map_err(D::Error::custom)?
1768 {
1769 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1770 _ => unreachable!(),
1771 },
1772 "not_captured" => match serde_json::from_value(value.into_value())
1773 .map_err(D::Error::custom)?
1774 {
1775 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1776 _ => unreachable!(),
1777 },
1778 _ => Ok(Self::Unknown { tag, body: value }),
1779 }
1780 }
1781}
1782
1783impl Serialize for StderrTailEntry {
1784 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1785 where
1786 S: Serializer,
1787 {
1788 match self {
1789 Self::Line {
1790 text,
1791 truncated,
1792 at_ms,
1793 } => StderrTailEntryWire::Line {
1794 text: text.clone(),
1795 truncated: *truncated,
1796 at_ms: *at_ms,
1797 }
1798 .serialize(serializer),
1799 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1800 Self::Unknown { body, .. } => body.serialize(serializer),
1801 }
1802 }
1803}
1804
1805impl<'de> Deserialize<'de> for StderrTailEntry {
1806 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1807 where
1808 D: serde::Deserializer<'de>,
1809 {
1810 let (tag, value) = read_tagged(deserializer, "kind")?;
1811 match tag.as_str() {
1812 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1813 StderrTailEntryWire::Line {
1814 text,
1815 truncated,
1816 at_ms,
1817 } => Ok(Self::Line {
1818 text,
1819 truncated,
1820 at_ms,
1821 }),
1822 _ => unreachable!(),
1823 },
1824 "process_start" => {
1825 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1826 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1827 _ => unreachable!(),
1828 }
1829 }
1830 _ => Ok(Self::Unknown { tag, body: value }),
1831 }
1832 }
1833}
1834
1835fn is_zero_u64(value: &u64) -> bool {
1836 *value == 0
1837}
1838
1839fn default_true() -> bool {
1840 true
1841}
1842
1843#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1845pub struct TerminalHistory {
1846 pub daemon_started_at_ms: u64,
1848 pub entries: Vec<TerminalEntry>,
1849 #[serde(default, skip_serializing_if = "is_zero_u64")]
1852 pub dropped: u64,
1853 #[serde(default, skip_serializing_if = "is_zero_u64")]
1856 pub journal_skipped_lines: u64,
1857 #[serde(default, skip_serializing_if = "is_zero_u64")]
1859 pub journal_read_errors: u64,
1860 #[serde(default, skip_serializing_if = "is_zero_u64")]
1862 pub journal_write_failures: u64,
1863}
1864
1865#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1867pub struct TerminalEntry {
1868 #[serde(default, skip_serializing_if = "Option::is_none")]
1871 pub daemon_incarnation: Option<String>,
1872 #[serde(default, skip_serializing_if = "Option::is_none")]
1873 pub exit_code: Option<i32>,
1874 #[serde(default, skip_serializing_if = "Option::is_none")]
1875 pub exit_signal: Option<i32>,
1876 pub at_ms: u64,
1877 pub disposition: TerminalDisposition,
1878 #[serde(default, skip_serializing_if = "Option::is_none")]
1882 pub exit_kind: Option<TerminalExitKind>,
1883 #[serde(default, skip_serializing_if = "Option::is_none")]
1890 pub disposition_detail: Option<String>,
1891}
1892
1893#[derive(Debug, Clone, PartialEq, Eq)]
1898pub enum TerminalExitKind {
1899 Clean,
1900 Crash,
1901 DeliberateSeverance,
1902 Unknown(String),
1903}
1904
1905impl TerminalExitKind {
1906 fn wire_name(&self) -> &str {
1907 match self {
1908 Self::Clean => "clean",
1909 Self::Crash => "crash",
1910 Self::DeliberateSeverance => "deliberate_severance",
1911 Self::Unknown(value) => value,
1912 }
1913 }
1914}
1915
1916impl Serialize for TerminalExitKind {
1917 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1918 where
1919 S: serde::Serializer,
1920 {
1921 serializer.serialize_str(self.wire_name())
1922 }
1923}
1924
1925impl<'de> Deserialize<'de> for TerminalExitKind {
1926 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1927 where
1928 D: serde::Deserializer<'de>,
1929 {
1930 let value = String::deserialize(deserializer)?;
1931 Ok(match value.as_str() {
1932 "clean" => Self::Clean,
1933 "crash" => Self::Crash,
1934 "deliberate_severance" => Self::DeliberateSeverance,
1935 _ => Self::Unknown(value),
1936 })
1937 }
1938}
1939
1940open_string_enum! {
1941 TerminalDisposition {
1943 Stopped => "stopped",
1944 Disabled => "disabled",
1945 Failed => "failed",
1946 Restarting => "restarting",
1947 DaemonShutdown => "daemon_shutdown",
1952 }
1953}
1954
1955#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1956#[serde(rename_all = "snake_case")]
1957pub enum PollKind {
1958 Status,
1959 Liveness,
1960}
1961
1962#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1974#[non_exhaustive]
1975pub struct CatalogEntry {
1976 pub module_id: String,
1977 #[serde(default = "default_true")]
1988 pub ready: bool,
1989 #[serde(default, skip_serializing_if = "Option::is_none")]
1993 pub not_ready: Option<NotReadyReason>,
1994 #[serde(default, skip_serializing_if = "Option::is_none")]
2015 pub module_version: Option<String>,
2016 pub roles: Vec<ProviderRole>,
2017 pub control_ops: Vec<String>,
2018 #[serde(default, skip_serializing_if = "Option::is_none")]
2023 pub capabilities: Option<CapabilityDeclarations>,
2024 #[serde(default, skip_serializing_if = "Option::is_none")]
2027 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2028 #[serde(default, skip_serializing_if = "Option::is_none")]
2032 pub events: Option<Vec<EventDeclaration>>,
2033 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2036 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2037 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2040 pub operation_payload: BTreeMap<String, OperationPayload>,
2041 #[serde(default, skip_serializing_if = "Option::is_none")]
2047 pub flow_operations: Option<Vec<String>>,
2048 #[serde(default, skip_serializing_if = "Option::is_none")]
2054 pub confirm_operations: Option<Vec<String>>,
2055 #[serde(default, skip_serializing_if = "Option::is_none")]
2058 pub rich_ui: Option<RichUiDescriptor>,
2059 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2062 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2063 #[serde(default, skip_serializing_if = "is_false")]
2066 pub nonce_verified: bool,
2067}
2068
2069impl CatalogEntry {
2070 #[must_use]
2072 pub fn new(
2073 module_id: impl Into<String>,
2074 roles: Vec<ProviderRole>,
2075 control_ops: Vec<String>,
2076 ) -> Self {
2077 Self {
2078 module_id: module_id.into(),
2079 ready: default_true(),
2080 not_ready: None,
2081 module_version: None,
2082 roles,
2083 control_ops,
2084 capabilities: None,
2085 self_signals: None,
2086 events: None,
2087 operation_delivery: BTreeMap::new(),
2088 operation_payload: BTreeMap::new(),
2089 flow_operations: None,
2090 confirm_operations: None,
2091 rich_ui: None,
2092 role_declarations: BTreeMap::new(),
2093 nonce_verified: false,
2094 }
2095 }
2096
2097 #[must_use]
2099 pub fn with_operation_payload(
2100 mut self,
2101 operation_payload: BTreeMap<String, OperationPayload>,
2102 ) -> Self {
2103 self.operation_payload = operation_payload;
2104 self
2105 }
2106
2107 #[must_use]
2110 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2111 self.flow_operations = flow_operations;
2112 self
2113 }
2114
2115 #[must_use]
2118 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2119 self.confirm_operations = confirm_operations;
2120 self
2121 }
2122
2123 #[must_use]
2125 pub fn with_ready(mut self, ready: bool) -> Self {
2126 self.ready = ready;
2127 self
2128 }
2129
2130 #[must_use]
2132 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2133 self.not_ready = not_ready;
2134 self
2135 }
2136
2137 #[must_use]
2139 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2140 self.module_version = module_version;
2141 self
2142 }
2143
2144 #[must_use]
2146 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2147 self.capabilities = capabilities;
2148 self
2149 }
2150
2151 #[must_use]
2153 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2154 self.self_signals = self_signals;
2155 self
2156 }
2157
2158 #[must_use]
2160 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2161 self.events = events;
2162 self
2163 }
2164
2165 #[must_use]
2168 pub fn with_operation_delivery(
2169 mut self,
2170 operation_delivery: BTreeMap<String, OperationDelivery>,
2171 ) -> Self {
2172 self.operation_delivery = operation_delivery;
2173 self
2174 }
2175
2176 #[must_use]
2178 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2179 self.rich_ui = rich_ui;
2180 self
2181 }
2182
2183 #[must_use]
2185 pub fn with_role_declarations(
2186 mut self,
2187 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2188 ) -> Self {
2189 self.role_declarations = role_declarations;
2190 self
2191 }
2192
2193 #[must_use]
2196 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2197 self.nonce_verified = nonce_verified;
2198 self
2199 }
2200}
2201
2202fn is_false(value: &bool) -> bool {
2203 !value
2204}
2205
2206#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2208pub struct NotReadyReason {
2209 pub reason: String,
2214 #[serde(default, skip_serializing_if = "Option::is_none")]
2217 pub capability: Option<String>,
2218}
2219
2220impl NotReadyReason {
2221 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2222 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2223}
2224
2225#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2226pub struct CapabilityRequirementStatus {
2227 pub consumer: String,
2228 pub capability: String,
2229 pub need: String,
2230 pub verdict: String,
2231 pub episode_seq: u64,
2232 pub config_satisfiable: bool,
2233 pub runtime_available: bool,
2234 pub detail: String,
2235}
2236
2237#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2238pub struct SupervisorRescanResult {
2239 pub added: Vec<String>,
2240 pub removed: Vec<String>,
2241 pub changed_pending_reload: Vec<String>,
2242 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2255 pub enabled_changes: Vec<String>,
2256 pub unchanged: u32,
2257 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2265 pub preview: bool,
2266 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2284 pub restart_required: Vec<String>,
2285 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2289 pub capability_warnings: Vec<String>,
2290 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2297 pub module_actions: Vec<RescanModuleAction>,
2298 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2302 pub earlier_pending: Vec<String>,
2303 #[serde(default, skip_serializing_if = "Option::is_none")]
2306 pub expect: Option<RescanExpect>,
2307}
2308
2309#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2325#[serde(rename_all = "snake_case")]
2326pub enum ModuleProtocol {
2327 #[default]
2331 Subc,
2332 None,
2341}
2342
2343#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2355#[non_exhaustive]
2356pub struct SupervisorEntry {
2357 #[serde(default, skip_serializing_if = "Option::is_none")]
2360 pub waiting_for_previous_pid: Option<u32>,
2361 pub module_id: String,
2362 pub state: String,
2363 #[serde(default, skip_serializing_if = "Option::is_none")]
2367 pub next_retry_at_ms: Option<u64>,
2368 pub enabled: bool,
2369 #[serde(default, skip_serializing_if = "Option::is_none")]
2372 pub configured_enabled: Option<bool>,
2373 pub live: bool,
2383 #[serde(default)]
2387 pub protocol: ModuleProtocol,
2388 #[serde(default, skip_serializing_if = "Option::is_none")]
2391 pub launch_nonce_env: Option<bool>,
2392 #[serde(default, skip_serializing_if = "Option::is_none")]
2398 pub launch_nonce_source: Option<String>,
2399 pub health: SupervisorHealthStatus,
2400 #[serde(default, skip_serializing_if = "Option::is_none")]
2403 pub pending_reload: Option<PendingReloadVerdict>,
2404 #[serde(default)]
2410 pub last_probe_ms: Option<u64>,
2411 #[serde(default, skip_serializing_if = "Option::is_none")]
2415 pub last_exit_code: Option<i32>,
2416 #[serde(default, skip_serializing_if = "Option::is_none")]
2420 pub last_exit_signal: Option<i32>,
2421 #[serde(default, skip_serializing_if = "Option::is_none")]
2425 pub last_exit_ms: Option<u64>,
2426 #[serde(default, skip_serializing_if = "Option::is_none")]
2429 pub last_exit_kind: Option<TerminalExitKind>,
2430 #[serde(default, skip_serializing_if = "Option::is_none")]
2447 pub restart_count: Option<u32>,
2448 #[serde(default, skip_serializing_if = "Option::is_none")]
2451 pub max_restarts: Option<u32>,
2452 #[serde(default, skip_serializing_if = "Option::is_none")]
2455 pub lifetime_restarts: Option<u32>,
2456 #[serde(default, skip_serializing_if = "Option::is_none")]
2460 pub spawn_generation: Option<u64>,
2461 #[serde(default, skip_serializing_if = "Option::is_none")]
2471 pub restart_window_secs: Option<u64>,
2472 #[serde(default, skip_serializing_if = "Option::is_none")]
2476 pub drain_timeout_ms: Option<u64>,
2477 #[serde(default, skip_serializing_if = "Option::is_none")]
2480 pub restart_backoff_ms: Option<u64>,
2481 #[serde(default, skip_serializing_if = "Option::is_none")]
2484 pub restart_max_backoff_ms: Option<u64>,
2485 #[serde(default, skip_serializing_if = "Option::is_none")]
2498 pub resources: Option<ChildResourceUsage>,
2499}
2500
2501impl SupervisorEntry {
2502 #[must_use]
2504 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2505 self.next_retry_at_ms = next_retry_at_ms;
2506 self
2507 }
2508
2509 #[must_use]
2511 pub fn new(
2512 module_id: impl Into<String>,
2513 state: impl Into<String>,
2514 enabled: bool,
2515 live: bool,
2516 health: SupervisorHealthStatus,
2517 ) -> Self {
2518 Self {
2519 module_id: module_id.into(),
2520 state: state.into(),
2521 next_retry_at_ms: None,
2522 waiting_for_previous_pid: None,
2523 enabled,
2524 configured_enabled: None,
2525 live,
2526 protocol: ModuleProtocol::default(),
2527 launch_nonce_env: None,
2528 launch_nonce_source: None,
2529 health,
2530 pending_reload: None,
2531 last_probe_ms: None,
2532 last_exit_code: None,
2533 last_exit_signal: None,
2534 last_exit_ms: None,
2535 last_exit_kind: None,
2536 restart_count: None,
2537 max_restarts: None,
2538 lifetime_restarts: None,
2539 spawn_generation: None,
2540 restart_window_secs: None,
2541 drain_timeout_ms: None,
2542 restart_backoff_ms: None,
2543 restart_max_backoff_ms: None,
2544 resources: None,
2545 }
2546 }
2547
2548 #[must_use]
2550 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2551 self.protocol = protocol;
2552 self
2553 }
2554
2555 #[must_use]
2557 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2558 self.configured_enabled = configured_enabled;
2559 self
2560 }
2561
2562 #[must_use]
2564 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2565 self.launch_nonce_env = launch_nonce_env;
2566 self
2567 }
2568
2569 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2570 self.launch_nonce_source = source;
2571 self
2572 }
2573
2574 #[must_use]
2575 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2576 self.waiting_for_previous_pid = pid;
2577 self
2578 }
2579
2580 #[must_use]
2582 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2583 self.pending_reload = pending_reload;
2584 self
2585 }
2586
2587 #[must_use]
2589 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2590 self.last_probe_ms = last_probe_ms;
2591 self
2592 }
2593
2594 #[must_use]
2596 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2597 self.last_exit_code = last_exit_code;
2598 self
2599 }
2600
2601 #[must_use]
2603 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2604 self.last_exit_signal = last_exit_signal;
2605 self
2606 }
2607
2608 #[must_use]
2610 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2611 self.last_exit_ms = last_exit_ms;
2612 self
2613 }
2614
2615 #[must_use]
2617 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2618 self.last_exit_kind = last_exit_kind;
2619 self
2620 }
2621
2622 #[must_use]
2624 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2625 self.restart_count = restart_count;
2626 self
2627 }
2628
2629 #[must_use]
2631 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2632 self.max_restarts = max_restarts;
2633 self
2634 }
2635
2636 #[must_use]
2638 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2639 self.lifetime_restarts = lifetime_restarts;
2640 self
2641 }
2642
2643 #[must_use]
2645 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2646 self.spawn_generation = spawn_generation;
2647 self
2648 }
2649
2650 #[must_use]
2652 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2653 self.restart_window_secs = restart_window_secs;
2654 self
2655 }
2656
2657 #[must_use]
2659 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2660 self.drain_timeout_ms = drain_timeout_ms;
2661 self
2662 }
2663
2664 #[must_use]
2666 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2667 self.restart_backoff_ms = restart_backoff_ms;
2668 self
2669 }
2670
2671 #[must_use]
2673 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2674 self.restart_max_backoff_ms = restart_max_backoff_ms;
2675 self
2676 }
2677
2678 #[must_use]
2680 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2681 self.resources = resources;
2682 self
2683 }
2684}
2685
2686#[derive(Debug, Clone, PartialEq)]
2689pub enum ChildResourceUsage {
2690 Measured(ChildResourceReading),
2691 Unavailable {
2692 reason: ChildResourceUnavailableReason,
2693 },
2694 Unknown {
2697 tag: String,
2698 body: OrderedJsonObject,
2699 },
2700}
2701
2702#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2704pub struct ChildResourceReading {
2705 pub memory_bytes: u64,
2708 pub memory_kind: ChildMemoryKind,
2709 #[serde(default, skip_serializing_if = "Option::is_none")]
2712 pub swap_bytes: Option<u64>,
2713 pub cpu_user_ms: u64,
2717 pub cpu_system_ms: u64,
2720}
2721
2722open_string_enum! {
2723 ChildMemoryKind {
2725 PhysFootprint => "phys_footprint",
2729 ResidentSet => "resident_set",
2732 WindowsWorkingSet => "windows_working_set",
2735 }
2736}
2737
2738open_string_enum! {
2739 ChildResourceUnavailableReason {
2741 NotRunning => "not_running",
2743 UnsupportedPlatform => "unsupported_platform",
2745 Unreadable => "unreadable",
2748 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2751 }
2752}
2753
2754#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2755#[serde(rename_all = "snake_case")]
2756pub enum SupervisorHealthStatus {
2757 Ok,
2758 Degraded,
2759 Failing,
2760 Unresponsive,
2761 Unknown,
2762}
2763
2764#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2765pub struct SupervisorHealthEntry {
2766 pub module_id: String,
2767 pub status: SupervisorHealthStatus,
2768 #[serde(default, skip_serializing_if = "Option::is_none")]
2774 pub detail: Option<String>,
2775 #[serde(default, skip_serializing_if = "Option::is_none")]
2780 pub metrics: Option<serde_json::Value>,
2781 pub consecutive_failures: u32,
2782 #[serde(default)]
2785 pub late_answer_count: u64,
2786 #[serde(default, skip_serializing_if = "Option::is_none")]
2788 pub last_late_answer_latency_ms: Option<u64>,
2789 #[serde(default)]
2794 pub last_action: Option<String>,
2795 #[serde(default)]
2798 pub last_action_ms: Option<u64>,
2799 #[serde(default, skip_serializing_if = "Option::is_none")]
2812 pub last_probe_ms: Option<u64>,
2813}
2814
2815#[cfg(test)]
2816mod tests {
2817 #[test]
2818 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2819 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2820 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2821 assert_eq!(decoded.configured_enabled, None);
2822 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2823 }
2824
2825 #[test]
2826 fn configured_enabled_values_round_trip_in_list() {
2827 for enabled in [false, true] {
2828 let entry = SupervisorEntry::new(
2829 "provider",
2830 "running",
2831 true,
2832 true,
2833 SupervisorHealthStatus::Unknown,
2834 )
2835 .with_configured_enabled(Some(enabled));
2836 let entry_json = serde_json::to_value(&entry).unwrap();
2837 assert_eq!(entry_json["configured_enabled"], enabled);
2838 assert_eq!(
2839 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
2840 entry
2841 );
2842 }
2843 }
2844
2845 #[test]
2846 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2847 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2848 volume_serial_number: u64::MAX,
2849 file_id: [
2850 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2851 ],
2852 };
2853 let agreement = super::RunningImageAgreement::Match { evidence };
2854 let encoded = serde_json::to_string(&agreement).unwrap();
2855 assert!(encoded.contains("windows_spawn_file_id"));
2856 assert_eq!(
2857 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
2858 agreement
2859 );
2860 }
2861
2862 #[test]
2863 fn unix_running_image_evidence_keeps_original_wire_bytes() {
2864 assert_eq!(
2865 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
2866 device: 7,
2867 inode: 11
2868 })
2869 .unwrap(),
2870 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
2871 );
2872 assert_eq!(
2873 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
2874 digest: "abc".to_owned()
2875 })
2876 .unwrap(),
2877 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
2878 );
2879 }
2880 use super::*;
2881 use subc_protocol::{BindIdentity, RouteTarget};
2882
2883 #[test]
2884 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2885 let entry = TerminalEntry {
2886 daemon_incarnation: Some("daemon-before-restart".into()),
2887 exit_code: Some(1),
2888 exit_signal: None,
2889 at_ms: 1_700_000_000_123,
2890 disposition: TerminalDisposition::Restarting,
2891 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2892 disposition_detail: None,
2893 };
2894 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2895 assert_eq!(
2896 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2897 ["exit_kind"],
2898 "deliberate_severance"
2899 );
2900
2901 #[derive(serde::Deserialize)]
2902 struct LegacyTerminalEntry {
2903 exit_code: Option<i32>,
2904 exit_signal: Option<i32>,
2905 at_ms: u64,
2906 disposition: TerminalDisposition,
2907 }
2908
2909 let decoded: LegacyTerminalEntry =
2910 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2911 assert_eq!(decoded.exit_code, Some(1));
2912 assert_eq!(decoded.exit_signal, None);
2913 assert_eq!(decoded.at_ms, 1_700_000_000_123);
2914 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
2915
2916 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
2917 let future: TerminalEntry =
2918 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
2919 assert_eq!(
2920 future.exit_kind,
2921 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
2922 );
2923 }
2924
2925 #[test]
2926 fn terminal_incarnation_is_optional_for_older_daemons() {
2927 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
2928 "at_ms": 123,
2929 "disposition": "stopped"
2930 }))
2931 .unwrap();
2932 let encoded = serde_json::to_value(&entry).unwrap();
2933 assert_eq!(
2934 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
2935 (None, None)
2936 );
2937 }
2938
2939 #[test]
2940 fn route_poll_uses_kind_field() {
2941 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
2942 route_channel: 7,
2943 route_epoch: 11,
2944 kind: PollKind::Status,
2945 })
2946 .unwrap();
2947
2948 assert_eq!(body["op"], "route.poll");
2949 assert_eq!(body["route_epoch"], 11);
2950 assert_eq!(body["kind"], "status");
2951 assert!(body.get("op").is_some());
2952 }
2953
2954 #[test]
2955 fn route_open_is_internally_tagged() {
2956 let request = ClientControlRequest::RouteOpen {
2957 target: RouteTarget::ToolProvider {
2958 module_id: "aft".to_string(),
2959 },
2960 identity: BindIdentity::new("/tmp/project", "opencode", "session-1"),
2961 consumer_identity: None,
2962 consumer_capabilities: None,
2963 role_versions: None,
2964 admission_facts: None,
2965 scope: None,
2966 };
2967
2968 let body = serde_json::to_value(request).unwrap();
2969 assert_eq!(body["op"], "route.open");
2970 assert_eq!(body["target"]["kind"], "tool_provider");
2971 assert!(body.get("consumer_identity").is_none());
2972 assert!(body.get("consumer_capabilities").is_none());
2973 assert!(body.get("role_versions").is_none());
2974 }
2975
2976 #[test]
2977 fn route_open_without_optional_fields_still_decodes() {
2978 let body = serde_json::json!({
2979 "op": "route.open",
2980 "target": { "kind": "tool_provider", "module_id": "aft" },
2981 "identity": {
2982 "project_root": "/tmp/project",
2983 "harness": "opencode",
2984 "session": "session-1"
2985 }
2986 });
2987
2988 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
2989 let ClientControlRequest::RouteOpen {
2990 consumer_identity,
2991 consumer_capabilities,
2992 role_versions,
2993 admission_facts,
2994 ..
2995 } = decoded
2996 else {
2997 panic!("decoded wrong request variant");
2998 };
2999 assert_eq!(consumer_identity, None);
3000 assert_eq!(consumer_capabilities, None);
3001 assert_eq!(role_versions, None);
3002 assert_eq!(admission_facts, None);
3003 }
3004
3005 #[test]
3006 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3007 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3008 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3009 match decoded {
3010 ClientControlPush::RouteClosed {
3011 excluded_subscriptions,
3012 terminal,
3013 ..
3014 } => {
3015 assert_eq!(excluded_subscriptions, 0);
3016 assert_eq!(terminal, None);
3017 }
3018 other => panic!("unexpected push: {other:?}"),
3019 }
3020 assert!(!serde_json::to_string(&decoded)
3021 .unwrap()
3022 .contains("terminal"));
3023 }
3024
3025 #[test]
3026 fn old_route_closed_decoder_ignores_new_terminal_field() {
3027 #[derive(serde::Deserialize)]
3028 #[serde(tag = "op")]
3029 enum LegacyClientControlPush {
3030 #[serde(rename = "route.closed")]
3031 RouteClosed {
3032 module_id: String,
3033 reason: RouteCloseReason,
3034 drained: bool,
3035 abandoned: u32,
3036 },
3037 }
3038
3039 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3040 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3041 match decoded {
3042 LegacyClientControlPush::RouteClosed {
3043 module_id,
3044 reason,
3045 drained,
3046 abandoned,
3047 } => {
3048 assert_eq!(module_id, "aft-tools");
3049 assert_eq!(reason, RouteCloseReason::Crash);
3050 assert!(!drained);
3051 assert_eq!(abandoned, 0);
3052 }
3053 }
3054 }
3055
3056 #[test]
3057 fn supervisor_routes_is_a_control_plane_request() {
3058 let body = serde_json::json!({
3059 "op": "supervisor.routes",
3060 "module_id": "aft"
3061 });
3062
3063 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3064 assert_eq!(serde_json::to_value(request).unwrap(), body);
3065 }
3066
3067 #[test]
3068 fn diagnostic_string_enums_retain_unknown_wire_values() {
3069 let reason: RunningImageUnavailableReason =
3070 serde_json::from_str("\"future_reason\"").unwrap();
3071 let disposition: TerminalDisposition =
3072 serde_json::from_str("\"future_disposition\"").unwrap();
3073
3074 assert_eq!(
3075 reason,
3076 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3077 );
3078 assert_eq!(
3079 disposition,
3080 TerminalDisposition::Unknown("future_disposition".to_string())
3081 );
3082 }
3083
3084 #[test]
3085 fn diagnostic_string_enums_preserve_existing_wire_names() {
3086 let names = [
3087 (RunningImageUnavailableReason::NotRunning, "not_running"),
3088 (
3089 RunningImageUnavailableReason::UnsupportedPlatform,
3090 "unsupported_platform",
3091 ),
3092 (
3093 RunningImageUnavailableReason::RunningExecutableUnreadable,
3094 "running_executable_unreadable",
3095 ),
3096 (
3097 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3098 "running_executable_permission_denied",
3099 ),
3100 (
3101 RunningImageUnavailableReason::ProcessHidden,
3102 "process_hidden",
3103 ),
3104 (
3105 RunningImageUnavailableReason::SpawnedPathUnreadable,
3106 "spawned_path_unreadable",
3107 ),
3108 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3109 (
3110 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3111 "process_identity_unconfirmed",
3112 ),
3113 ];
3114 for (value, expected) in names {
3115 let wire = serde_json::to_string(&value).unwrap();
3116 assert_eq!(wire, format!("\"{expected}\""));
3117 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3118 assert_eq!(decoded, value);
3119 }
3120
3121 for (value, expected) in [
3122 (TerminalDisposition::Stopped, "stopped"),
3123 (TerminalDisposition::Disabled, "disabled"),
3124 (TerminalDisposition::Failed, "failed"),
3125 (TerminalDisposition::Restarting, "restarting"),
3126 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3127 ] {
3128 let wire = serde_json::to_string(&value).unwrap();
3129 assert_eq!(wire, format!("\"{expected}\""));
3130 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3131 assert_eq!(decoded, value);
3132 }
3133 }
3134
3135 #[test]
3136 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3137 let entry = SupervisorEntry::new(
3138 "waiting-module",
3139 "starting",
3140 true,
3141 false,
3142 SupervisorHealthStatus::Unknown,
3143 );
3144 let old_wire = serde_json::to_value(&entry).unwrap();
3145 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3146 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3147 assert_eq!(decoded.waiting_for_previous_pid, None);
3148 let entry = entry.with_waiting_for_previous_pid(Some(42));
3149 let wire = serde_json::to_value(&entry).unwrap();
3150 assert_eq!(wire["waiting_for_previous_pid"], 42);
3151 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3152 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3153 }
3154
3155 #[test]
3156 fn diagnostic_string_enums_reject_non_string_bodies() {
3157 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3158 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3159 }
3160
3161 #[test]
3162 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3163 let body = serde_json::json!({
3164 "op": "supervisor.provenance",
3165 "daemon": {
3166 "daemon_build": {},
3167 "daemon_observed": {
3168 "running_image": {
3169 "status": "unavailable",
3170 "reason": "not_running"
3171 }
3172 }
3173 },
3174 "modules": [
3175 {
3176 "module_id": "future",
3177 "module_declared": { "status": "unverifiable" },
3178 "daemon_observed": {
3179 "running_image": {
3180 "status": "unavailable",
3181 "reason": "future_reason"
3182 }
3183 }
3184 },
3185 {
3186 "module_id": "healthy-a",
3187 "module_declared": { "status": "unverifiable" },
3188 "daemon_observed": {
3189 "running_image": {
3190 "status": "match",
3191 "evidence": {
3192 "method": "linux_proc_sha256",
3193 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3194 }
3195 }
3196 }
3197 },
3198 {
3199 "module_id": "healthy-b",
3200 "module_declared": { "status": "unverifiable" },
3201 "daemon_observed": {
3202 "running_image": {
3203 "status": "unavailable",
3204 "reason": "unsupported_platform"
3205 }
3206 }
3207 }
3208 ]
3209 });
3210
3211 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3212 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3213 panic!("decoded wrong response variant");
3214 };
3215 assert_eq!(modules.len(), 3);
3216 assert_eq!(modules[0].module_id, "future");
3217 assert_eq!(
3218 modules[0].daemon_observed.running_image,
3219 RunningImageAgreement::Unavailable {
3220 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3221 }
3222 );
3223 assert_eq!(modules[1].module_id, "healthy-a");
3224 assert_eq!(modules[2].module_id, "healthy-b");
3225 }
3226
3227 #[test]
3228 fn tagged_unknown_values_retain_tag_and_body() {
3229 macro_rules! assert_unknown_round_trip {
3230 ($ty:ident, $field:literal, $value:expr) => {
3231 let value = $value;
3232 let wire = serde_json::to_string(&value).unwrap();
3233 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3234 match decoded {
3235 $ty::Unknown { tag, body } => {
3236 assert_eq!(tag, value[$field].as_str().unwrap());
3237 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3238 }
3239 _ => panic!("decoded known variant"),
3240 }
3241 };
3242 }
3243
3244 assert_unknown_round_trip!(
3245 ModuleDeclaredProvenance,
3246 "status",
3247 serde_json::json!({"status": "future", "build": {"version": 7}})
3248 );
3249 assert_unknown_round_trip!(
3250 RunningImageAgreement,
3251 "status",
3252 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3253 );
3254 assert_unknown_round_trip!(
3255 RunningImageEvidence,
3256 "method",
3257 serde_json::json!({"method": "future", "digest": "abc"})
3258 );
3259 assert_unknown_round_trip!(
3260 SupervisorRouteConsumer,
3261 "kind",
3262 serde_json::json!({"kind": "future", "module_id": "m"})
3263 );
3264 assert_unknown_round_trip!(
3265 StderrCaptureState,
3266 "state",
3267 serde_json::json!({"state": "future", "reason": "because"})
3268 );
3269 assert_unknown_round_trip!(
3270 StderrTailEntry,
3271 "kind",
3272 serde_json::json!({"kind": "future", "text": "line"})
3273 );
3274 assert_unknown_round_trip!(
3275 ChildResourceUsage,
3276 "status",
3277 serde_json::json!({"status": "future", "memory_bytes": 1})
3278 );
3279 }
3280
3281 #[test]
3282 fn child_resource_usage_round_trips_both_known_states() {
3283 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3284 memory_bytes: 0,
3285 memory_kind: ChildMemoryKind::ResidentSet,
3286 swap_bytes: Some(0),
3287 cpu_user_ms: 0,
3288 cpu_system_ms: 0,
3289 });
3290 let wire = serde_json::to_value(&measured).unwrap();
3291 assert_eq!(
3292 wire,
3293 serde_json::json!({
3294 "status": "measured",
3295 "memory_bytes": 0,
3296 "memory_kind": "resident_set",
3297 "swap_bytes": 0,
3298 "cpu_user_ms": 0,
3299 "cpu_system_ms": 0
3300 })
3301 );
3302 assert_eq!(
3303 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3304 measured
3305 );
3306
3307 let unavailable = ChildResourceUsage::Unavailable {
3308 reason: ChildResourceUnavailableReason::NotRunning,
3309 };
3310 let wire = serde_json::to_value(&unavailable).unwrap();
3311 assert_eq!(
3312 wire,
3313 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3314 );
3315 assert_eq!(
3316 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3317 unavailable
3318 );
3319 }
3320
3321 #[test]
3322 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3323 let stamped: StderrTailEntry = serde_json::from_str(
3327 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3328 )
3329 .unwrap();
3330 assert_eq!(
3331 stamped,
3332 StderrTailEntry::Line {
3333 text: "boom".to_string(),
3334 truncated: true,
3335 at_ms: Some(1_789_801_440_685),
3336 }
3337 );
3338 let unstamped: StderrTailEntry =
3339 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3340 assert_eq!(
3341 unstamped,
3342 StderrTailEntry::Line {
3343 text: "boom".to_string(),
3344 truncated: false,
3345 at_ms: None,
3346 }
3347 );
3348 assert_eq!(
3351 serde_json::to_string(&unstamped).unwrap(),
3352 r#"{"kind":"line","text":"boom"}"#
3353 );
3354 assert_eq!(
3355 serde_json::to_value(&stamped).unwrap()["at_ms"],
3356 serde_json::json!(1_789_801_440_685u64)
3357 );
3358 }
3359
3360 #[test]
3361 fn tagged_unknown_values_round_trip_the_original_json() {
3362 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3363 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3364 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3365 }
3366
3367 #[test]
3368 fn tagged_unknown_values_round_trip_trailing_tag() {
3369 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3370 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3371 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3372
3373 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3374 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3375 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3376 }
3377
3378 #[test]
3379 fn tagged_unknown_values_round_trip_middle_tag() {
3380 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3381 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3382 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3383
3384 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3385 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3386 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3387 }
3388
3389 #[test]
3390 fn tagged_unknown_values_round_trip_deep_payload() {
3391 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3392 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3393 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3394
3395 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3396 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3397 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3398 }
3399
3400 #[test]
3401 fn tagged_unknown_values_reject_non_object_bodies() {
3402 for wire in ["42", r#""future""#, "[]"] {
3403 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3404 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3405 }
3406 }
3407
3408 #[test]
3409 fn duplicate_discriminators_reject_without_panicking() {
3410 assert_eq!(
3411 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3412 .unwrap(),
3413 ModuleDeclaredProvenance::Unverifiable
3414 );
3415 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3416 .unwrap()
3417 {
3418 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3419 _ => panic!("future discriminator decoded as a known variant"),
3420 }
3421
3422 let wires = [
3423 r#"{"status":"reported","status":"unverifiable"}"#,
3424 r#"{"status":"unverifiable","status":"reported"}"#,
3425 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3426 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3427 ];
3428
3429 for wire in wires {
3430 let result =
3431 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3432 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3433 assert!(
3434 result.unwrap().is_err(),
3435 "duplicate discriminator decoded: {wire}"
3436 );
3437 }
3438
3439 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3440 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3441 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3442 assert!(
3443 result.unwrap().is_err(),
3444 "duplicate discriminator decoded: {wire}"
3445 );
3446 }
3447
3448 #[test]
3449 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3450 let known_wire =
3451 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3452 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3453 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3454
3455 for wire in [
3456 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3457 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3458 ] {
3459 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3460 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3461 }
3462
3463 for wire in [
3464 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3465 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3466 ] {
3467 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3468 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3469 }
3470
3471 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3472 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3473 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3474
3475 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3476 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3477 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3478 }
3479
3480 #[test]
3481 fn tagged_unknown_member_does_not_discard_known_siblings() {
3482 let body = serde_json::json!({
3483 "modules": [{
3484 "module_id": "target",
3485 "routes": [
3486 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3487 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3488 ]
3489 }]
3490 });
3491 let decoded: ClientControlResponse = serde_json::from_value(
3492 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3493 )
3494 .unwrap();
3495 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3496 panic!("decoded wrong response variant");
3497 };
3498 assert_eq!(modules[0].routes.len(), 2);
3499 assert_eq!(
3500 modules[0].routes[1].consumer,
3501 SupervisorRouteConsumer::Direct { connection_id: 7 }
3502 );
3503 }
3504}
3505
3506#[cfg(test)]
3507mod launch_nonce_redaction_tests {
3508 use super::*;
3509
3510 const NONCE: &str = "nonce-f00dfeed1234abcd";
3511
3512 fn identity() -> ConsumerIdentity {
3513 ConsumerIdentity {
3514 module_id: "wernicke".to_string(),
3515 launch_nonce: NONCE.to_string(),
3516 }
3517 }
3518
3519 #[test]
3520 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3521 let printed = format!("{:?}", identity());
3522 assert!(printed.contains("wernicke"), "{printed}");
3523 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3524 }
3525
3526 #[test]
3527 fn route_open_request_debug_never_prints_the_nonce() {
3528 let request = ClientControlRequest::RouteOpen {
3529 target: subc_protocol::RouteTarget::ToolProvider {
3530 module_id: "broca".to_string(),
3531 },
3532 identity: subc_protocol::BindIdentity::new(
3533 PathBuf::from("/tmp/project"),
3534 "test".to_string(),
3535 "session".to_string(),
3536 ),
3537 consumer_identity: Some(identity()),
3538 consumer_capabilities: None,
3539 role_versions: None,
3540 admission_facts: None,
3541 scope: None,
3542 };
3543 let printed = format!("{request:?}");
3544 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3545 }
3546}