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