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 ProviderRole, 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
32macro_rules! open_string_enum {
33 (
34 $(#[$meta:meta])*
35 $name:ident {
36 $( $(#[$variant_meta:meta])* $variant:ident => $wire_name:literal ),+ $(,)?
37 }
38 ) => {
39 $(#[$meta])*
40 #[derive(Debug, Clone, PartialEq, Eq)]
41 pub enum $name {
42 $( $(#[$variant_meta])* $variant, )+
43 Unknown(String),
44 }
45
46 impl $name {
47 fn wire_name(&self) -> &str {
48 match self {
49 $( Self::$variant => $wire_name, )+
50 Self::Unknown(value) => value,
51 }
52 }
53 }
54
55 impl Serialize for $name {
56 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
57 where
58 S: serde::Serializer,
59 {
60 serializer.serialize_str(self.wire_name())
61 }
62 }
63
64 impl<'de> Deserialize<'de> for $name {
65 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
66 where
67 D: serde::Deserializer<'de>,
68 {
69 let value = String::deserialize(deserializer)?;
70 Ok(match value.as_str() {
71 $( $wire_name => Self::$variant, )+
72 _ => Self::Unknown(value),
73 })
74 }
75 }
76 };
77}
78
79#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
81pub struct ConsumerIdentity {
82 pub module_id: String,
83 pub launch_nonce: String,
84}
85
86impl std::fmt::Debug for ConsumerIdentity {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 f.debug_struct("ConsumerIdentity")
93 .field("module_id", &self.module_id)
94 .field(
95 "launch_nonce",
96 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
97 )
98 .finish()
99 }
100}
101
102pub mod ops {
113 pub const SERVER: &str = "server.";
114 pub const CATALOG: &str = "catalog.";
115 pub const ROUTE: &str = "route.";
116 pub const SUPERVISOR: &str = "supervisor.";
117 pub const CONFIG: &str = "config.";
118
119 pub const SERVER_DESCRIBE: &str = "server.describe";
120 pub const CATALOG_LIST: &str = "catalog.list";
121 pub const ROUTE_OPEN: &str = "route.open";
122 pub const ROUTE_POLL: &str = "route.poll";
123 pub const ROUTE_CLOSING: &str = "route.closing";
124 pub const ROUTE_CLOSED: &str = "route.closed";
125 pub const SUPERVISOR_LIST: &str = "supervisor.list";
126 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
127 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
128 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
129 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
130 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
131 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
132 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
133 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
134 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
135 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
136 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
137 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
138 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
139 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
140 pub const ACTIVITY_RECORD: &str = "activity.record";
141 pub const ACTIVITY_QUERY: &str = "activity.query";
142 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
147#[serde(tag = "op")]
148#[allow(clippy::large_enum_variant)]
151pub enum ClientControlRequest {
152 #[serde(rename = "server.describe")]
153 ServerDescribe {},
154 #[serde(rename = "catalog.list")]
155 CatalogList {
156 #[serde(default)]
161 module_id: Option<String>,
162 },
163 #[serde(rename = "route.open")]
164 RouteOpen {
165 target: RouteTarget,
166 identity: BindIdentity,
167 #[serde(default, skip_serializing_if = "Option::is_none")]
176 consumer_identity: Option<ConsumerIdentity>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
185 consumer_capabilities: Option<Vec<String>>,
186 #[serde(default, skip_serializing_if = "Option::is_none")]
197 role_versions: Option<BTreeMap<String, String>>,
198 #[serde(default, skip_serializing_if = "Option::is_none")]
200 admission_facts: Option<serde_json::Value>,
201 #[serde(default, skip_serializing_if = "Option::is_none")]
208 scope: Option<ScopeSelector>,
209 },
210 #[serde(rename = "route.poll")]
211 RoutePoll {
212 route_channel: u16,
213 route_epoch: u32,
214 kind: PollKind,
215 },
216 #[serde(rename = "supervisor.list")]
217 SupervisorList {},
218 #[serde(rename = "supervisor.spawn_snapshot")]
220 SupervisorSpawnSnapshot {},
221 #[serde(rename = "supervisor.spawn_subscribe")]
237 SupervisorSpawnSubscribe {
238 #[serde(default, skip_serializing_if = "Option::is_none")]
239 since: Option<SpawnCursor>,
240 },
241 #[serde(rename = "supervisor.restart")]
242 SupervisorRestart {
243 module_id: String,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
254 drain_timeout_ms: Option<u64>,
255 },
256 #[serde(rename = "supervisor.swap")]
271 SupervisorSwap {
272 module_id: String,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
276 ready_timeout_ms: Option<u64>,
277 },
278 #[serde(rename = "supervisor.reload")]
279 SupervisorReload { module_id: String },
280 #[serde(rename = "supervisor.rescan")]
281 SupervisorRescan {
282 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
302 preview: bool,
303 },
304 #[serde(rename = "supervisor.release_reserved")]
308 SupervisorReleaseReserved { module_id: String },
309 #[serde(rename = "supervisor.set_enabled")]
310 SupervisorSetEnabled { module_id: String, enabled: bool },
311 #[serde(rename = "supervisor.health_probe")]
312 SupervisorHealthProbe { module_id: String },
313 #[serde(rename = "supervisor.health")]
314 SupervisorHealth {},
315 #[serde(rename = "supervisor.routes")]
328 SupervisorRoutes {
329 #[serde(default, skip_serializing_if = "Option::is_none")]
330 module_id: Option<String>,
331 },
332 #[serde(rename = "supervisor.provenance")]
335 SupervisorProvenance {
336 #[serde(default, skip_serializing_if = "Option::is_none")]
337 module_id: Option<String>,
338 },
339 #[serde(rename = "supervisor.stderr_tail")]
347 SupervisorStderrTail {
348 module_id: String,
349 #[serde(default, skip_serializing_if = "Option::is_none")]
350 max_lines: Option<u32>,
351 #[serde(default, skip_serializing_if = "Option::is_none")]
352 max_bytes: Option<u32>,
353 },
354 #[serde(rename = "supervisor.terminals")]
367 SupervisorTerminals { module_id: String },
368}
369
370#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
372#[serde(tag = "op")]
373pub enum ClientControlResponse {
374 #[serde(rename = "server.describe")]
375 ServerDescribe {
376 protocol_ver: u8,
377 subc_ops: Vec<String>,
378 capabilities: Vec<String>,
379 connected_clients: u64,
380 #[serde(default, skip_serializing_if = "Option::is_none")]
381 counters: Option<serde_json::Value>,
382 #[serde(default, skip_serializing_if = "Option::is_none")]
389 build_git_sha: Option<String>,
390 #[serde(default, skip_serializing_if = "Option::is_none")]
396 build_lock_digest: Option<String>,
397 #[serde(default, skip_serializing_if = "Vec::is_empty")]
401 capability_requirements: Vec<CapabilityRequirementStatus>,
402 #[serde(default, skip_serializing_if = "Option::is_none")]
407 machine_id: Option<String>,
408 },
409 #[serde(rename = "catalog.list")]
410 CatalogList {
411 generation: u64,
412 modules: Vec<CatalogEntry>,
413 subc_ops: Vec<String>,
414 },
415 #[serde(rename = "route.open")]
416 RouteOpen {
417 route_channel: u16,
418 route_epoch: u32,
419 },
420 #[serde(rename = "route.poll")]
421 RoutePoll {
422 route_channel: u16,
423 route_epoch: u32,
424 status: Option<String>,
425 live: Option<bool>,
426 },
427 #[serde(rename = "supervisor.list")]
428 SupervisorList {
429 generation: u64,
430 modules: Vec<SupervisorEntry>,
431 },
432 #[serde(rename = "supervisor.spawn_snapshot")]
433 SupervisorSpawnSnapshot {
434 #[serde(flatten)]
435 snapshot: SpawnSnapshot,
436 },
437 #[serde(rename = "supervisor.ack")]
438 SupervisorAck { module_id: String, applied: bool },
439 #[serde(rename = "supervisor.rescan")]
440 SupervisorRescan {
441 #[serde(flatten)]
442 result: SupervisorRescanResult,
443 },
444 #[serde(rename = "supervisor.health_probe")]
445 SupervisorHealthProbe {
446 module_id: String,
447 status: HealthStatus,
448 #[serde(default, skip_serializing_if = "Option::is_none")]
449 detail: Option<String>,
450 #[serde(default, skip_serializing_if = "Option::is_none")]
451 metrics: Option<serde_json::Value>,
452 },
453 #[serde(rename = "supervisor.health")]
454 SupervisorHealth {
455 generation: u64,
456 modules: Vec<SupervisorHealthEntry>,
457 },
458 #[serde(rename = "supervisor.routes")]
459 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
460 #[serde(rename = "supervisor.provenance")]
461 SupervisorProvenance {
462 daemon: SupervisorDaemonProvenance,
463 modules: Vec<SupervisorModuleProvenance>,
464 },
465 #[serde(rename = "supervisor.stderr_tail")]
466 SupervisorStderrTail {
467 module_id: String,
468 #[serde(flatten)]
469 tail: StderrTail,
470 },
471 #[serde(rename = "supervisor.terminals")]
472 SupervisorTerminals {
473 module_id: String,
474 #[serde(flatten)]
475 terminals: TerminalHistory,
476 },
477}
478
479#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
484#[serde(tag = "op")]
485pub enum ClientControlPush {
486 #[serde(rename = "route.closing")]
487 RouteClosing {
488 module_id: String,
489 #[serde(default)]
492 channels: Vec<u16>,
493 reason: RouteCloseReason,
494 },
495 #[serde(rename = "route.closed")]
496 RouteClosed {
497 module_id: String,
498 #[serde(default)]
501 channels: Vec<u16>,
502 reason: RouteCloseReason,
503 drained: bool,
505 abandoned: u32,
508 #[serde(default)]
510 excluded_subscriptions: u32,
511 #[serde(default, skip_serializing_if = "Option::is_none")]
517 terminal: Option<bool>,
518 },
519}
520
521#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
523pub struct SpawnCursor {
524 pub daemon_incarnation: String,
525 pub seq: u64,
526}
527
528#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
530pub struct LiveSpawn {
531 pub module_id: String,
532 pub spawn_generation: u64,
533 pub pid: u32,
534 pub spawned_at_ms: u64,
535}
536
537#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
539pub struct SpawnSnapshot {
540 pub cursor: SpawnCursor,
541 pub ring_bound: u64,
543 pub live: Vec<LiveSpawn>,
544}
545
546#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
548#[serde(rename_all = "snake_case")]
549pub enum SpawnEventKind {
550 Spawned,
551 Exited,
552}
553
554#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
560pub struct SpawnEvent {
561 pub cursor: SpawnCursor,
562 pub kind: SpawnEventKind,
563 pub module_id: String,
564 pub spawn_generation: u64,
565 pub pid: u32,
566 #[serde(default, skip_serializing_if = "Option::is_none")]
567 pub exit_code: Option<i32>,
568 #[serde(default, skip_serializing_if = "Option::is_none")]
569 pub exit_signal: Option<i32>,
570}
571
572#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
574pub struct StderrTail {
575 pub capture: StderrCaptureState,
576 pub entries: Vec<StderrTailEntry>,
577 #[serde(default, skip_serializing_if = "is_zero_u64")]
586 pub dropped_lines: u64,
587}
588
589#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
591pub struct SupervisorRouteModule {
592 pub module_id: String,
593 pub routes: Vec<SupervisorRoute>,
594}
595
596#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
598pub struct SupervisorRoute {
599 pub consumer: SupervisorRouteConsumer,
600 pub age_ms: u64,
602 pub draining: bool,
605 #[serde(default, skip_serializing_if = "Option::is_none")]
611 pub drain_reason: Option<RouteCloseReason>,
612}
613
614#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
616pub struct SupervisorModuleProvenance {
617 pub module_id: String,
618 pub module_declared: ModuleDeclaredProvenance,
619 pub daemon_observed: SupervisorObservedProcess,
620}
621
622#[derive(Debug, Clone, PartialEq)]
624pub enum ModuleDeclaredProvenance {
625 Reported {
626 build: ManifestProvenance,
627 },
628 Unverifiable,
629 Unknown {
632 tag: String,
633 body: OrderedJsonObject,
634 },
635}
636
637#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
642pub struct SupervisorObservedProcess {
643 #[serde(default, skip_serializing_if = "Option::is_none")]
649 pub launch_nonce_source: Option<String>,
650 #[serde(default, skip_serializing_if = "Option::is_none")]
651 pub pid: Option<u32>,
652 #[serde(default, skip_serializing_if = "Option::is_none")]
653 pub spawned_at_ms: Option<u64>,
654 #[serde(default, skip_serializing_if = "Option::is_none")]
655 pub spawned_from: Option<PathBuf>,
656 pub running_image: RunningImageAgreement,
657}
658
659#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
662pub struct PendingReloadVerdict {
663 pub path: ReloadPathAgreement,
664 pub image: RunningImageAgreement,
665 #[serde(default, skip_serializing_if = "Option::is_none")]
666 pub spec: Option<LaunchSpecAgreement>,
667}
668
669#[cfg(test)]
670mod launch_spec_wire_tests {
671 use super::*;
672
673 #[test]
674 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
675 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
676 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
677 assert_eq!(parsed.spec, None);
678 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
679 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
680 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
681 assert!(
682 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
683 );
684 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
685 let unavailable = LaunchSpecAgreement::Unavailable {
686 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
687 };
688 let encoded = serde_json::to_string(&unavailable).unwrap();
689 assert_eq!(
690 encoded,
691 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
692 );
693 assert_eq!(
694 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
695 unavailable
696 );
697 }
698}
699
700#[derive(Debug, Clone, PartialEq)]
703pub enum LaunchSpecAgreement {
704 Match,
705 Mismatch,
706 Unavailable {
707 reason: LaunchSpecUnavailableReason,
708 },
709 Unknown {
710 tag: String,
711 body: OrderedJsonObject,
712 },
713}
714
715open_string_enum! {
716 LaunchSpecUnavailableReason {
717 NotRunning => "not_running",
718 SpawnedSpecUnavailable => "spawned_spec_unavailable",
719 }
720}
721
722#[derive(Debug, Clone, PartialEq)]
724pub enum ReloadPathAgreement {
725 Match,
726 Mismatch {
727 configured: PathBuf,
728 spawned_from: PathBuf,
729 },
730 Unavailable {
731 reason: ReloadPathUnavailableReason,
732 },
733 Unknown {
734 tag: String,
735 body: OrderedJsonObject,
736 },
737}
738
739open_string_enum! {
740 ReloadPathUnavailableReason {
742 NotRunning => "not_running",
743 SpawnedPathUnavailable => "spawned_path_unavailable",
744 }
745}
746
747#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
749pub struct SupervisorDaemonProvenance {
750 pub daemon_build: DaemonBuildProvenance,
751 pub daemon_observed: DaemonObservedProcess,
752}
753
754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
756pub struct DaemonBuildProvenance {
757 #[serde(default, skip_serializing_if = "Option::is_none")]
758 pub build_git_sha: Option<String>,
759 #[serde(default, skip_serializing_if = "Option::is_none")]
760 pub build_lock_digest: Option<String>,
761}
762
763#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
765pub struct DaemonObservedProcess {
766 #[serde(default, skip_serializing_if = "Option::is_none")]
767 pub pid: Option<u32>,
768 #[serde(default, skip_serializing_if = "Option::is_none")]
773 pub started_at_ms: Option<u64>,
774 pub running_image: RunningImageAgreement,
775}
776
777#[derive(Debug, Clone, PartialEq)]
779pub enum RunningImageAgreement {
780 Match {
781 evidence: RunningImageEvidence,
782 },
783 Mismatch {
784 running: RunningImageEvidence,
785 disk: RunningImageEvidence,
786 },
787 Unavailable {
788 reason: RunningImageUnavailableReason,
789 },
790 Unknown {
793 tag: String,
794 body: OrderedJsonObject,
795 },
796}
797
798#[derive(Debug, Clone, PartialEq)]
800pub enum RunningImageEvidence {
801 LinuxProcSha256 {
802 digest: String,
803 },
804 MacosSpawnInode {
805 device: u64,
806 inode: u64,
807 },
808 WindowsSpawnFileId {
810 volume_serial_number: u64,
811 file_id: [u8; 16],
812 },
813 Unknown {
816 tag: String,
817 body: OrderedJsonObject,
818 },
819}
820
821open_string_enum! {
822 RunningImageUnavailableReason {
824 NotRunning => "not_running",
825 UnsupportedPlatform => "unsupported_platform",
826 RunningExecutableUnreadable => "running_executable_unreadable",
827 RunningExecutablePermissionDenied => "running_executable_permission_denied",
828 ProcessHidden => "process_hidden",
829 SpawnedPathUnreadable => "spawned_path_unreadable",
830 HashFailed => "hash_failed",
831 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
832 }
833}
834
835#[derive(Debug, Clone, PartialEq)]
841pub enum SupervisorRouteConsumer {
842 Reserved {
843 module_id: String,
844 },
845 Direct {
846 connection_id: u64,
847 },
848 Unknown {
851 tag: String,
852 body: OrderedJsonObject,
853 },
854}
855
856#[derive(Debug, Clone, PartialEq)]
863pub enum StderrCaptureState {
864 Captured,
867 Incomplete { reason: String },
869 NotCaptured { reason: String },
871 Unknown {
874 tag: String,
875 body: OrderedJsonObject,
876 },
877}
878
879#[derive(Debug, Clone, PartialEq)]
880pub enum StderrTailEntry {
881 Line {
882 text: String,
883 truncated: bool,
888 at_ms: Option<u64>,
892 },
893 ProcessStart,
898 Unknown {
901 tag: String,
902 body: OrderedJsonObject,
903 },
904}
905
906#[derive(Debug, Serialize, Deserialize)]
907#[serde(tag = "status", rename_all = "snake_case")]
908enum ModuleDeclaredProvenanceWire {
909 Reported { build: ManifestProvenance },
910 Unverifiable,
911}
912
913#[derive(Debug, Serialize, Deserialize)]
914#[serde(tag = "status", rename_all = "snake_case")]
915enum RunningImageAgreementWire {
916 Match {
917 evidence: RunningImageEvidence,
918 },
919 Mismatch {
920 running: RunningImageEvidence,
921 disk: RunningImageEvidence,
922 },
923 Unavailable {
924 reason: RunningImageUnavailableReason,
925 },
926}
927
928#[derive(Debug, Serialize, Deserialize)]
929#[serde(tag = "status", rename_all = "snake_case")]
930enum ReloadPathAgreementWire {
931 Match,
932 Mismatch {
933 configured: PathBuf,
934 spawned_from: PathBuf,
935 },
936 Unavailable {
937 reason: ReloadPathUnavailableReason,
938 },
939}
940
941#[derive(Debug, Serialize, Deserialize)]
942#[serde(tag = "status", rename_all = "snake_case")]
943enum LaunchSpecAgreementWire {
944 Match,
945 Mismatch,
946 Unavailable { reason: LaunchSpecUnavailableReason },
947}
948
949#[derive(Debug, Serialize, Deserialize)]
950#[serde(tag = "method", rename_all = "snake_case")]
951enum RunningImageEvidenceWire {
952 LinuxProcSha256 {
953 digest: String,
954 },
955 MacosSpawnInode {
956 device: u64,
957 inode: u64,
958 },
959 WindowsSpawnFileId {
960 volume_serial_number: u64,
961 file_id: [u8; 16],
962 },
963}
964
965#[derive(Debug, Serialize, Deserialize)]
966#[serde(tag = "kind", rename_all = "snake_case")]
967enum SupervisorRouteConsumerWire {
968 Reserved { module_id: String },
969 Direct { connection_id: u64 },
970}
971
972#[derive(Debug, Serialize, Deserialize)]
973#[serde(tag = "state", rename_all = "snake_case")]
974enum StderrCaptureStateWire {
975 Captured,
976 Incomplete { reason: String },
977 NotCaptured { reason: String },
978}
979
980#[derive(Debug, Serialize, Deserialize)]
981#[serde(tag = "status", rename_all = "snake_case")]
982enum ChildResourceUsageWire {
983 Measured(ChildResourceReading),
984 Unavailable {
985 reason: ChildResourceUnavailableReason,
986 },
987}
988
989#[derive(Debug, Serialize, Deserialize)]
990#[serde(tag = "kind", rename_all = "snake_case")]
991enum StderrTailEntryWire {
992 Line {
993 text: String,
994 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
995 truncated: bool,
996 #[serde(default, skip_serializing_if = "Option::is_none")]
999 at_ms: Option<u64>,
1000 },
1001 ProcessStart,
1002}
1003
1004#[derive(Debug, Clone, PartialEq)]
1006pub enum OrderedJsonValue {
1007 Null,
1008 Bool(bool),
1009 Number(serde_json::Number),
1010 String(String),
1011 Array(Vec<Self>),
1012 Object(OrderedJsonObject),
1013}
1014
1015#[derive(Debug, Clone, PartialEq)]
1017pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1018
1019impl OrderedJsonObject {
1020 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1022 &self.0
1023 }
1024
1025 fn into_value(self) -> serde_json::Value {
1026 serde_json::Value::Object(
1027 self.0
1028 .into_iter()
1029 .map(|(key, value)| (key, value.into_value()))
1030 .collect(),
1031 )
1032 }
1033}
1034
1035impl OrderedJsonValue {
1036 fn into_value(self) -> serde_json::Value {
1037 match self {
1038 Self::Null => serde_json::Value::Null,
1039 Self::Bool(value) => serde_json::Value::Bool(value),
1040 Self::Number(value) => serde_json::Value::Number(value),
1041 Self::String(value) => serde_json::Value::String(value),
1042 Self::Array(values) => {
1043 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1044 }
1045 Self::Object(value) => value.into_value(),
1046 }
1047 }
1048}
1049
1050impl Serialize for OrderedJsonValue {
1051 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1052 where
1053 S: Serializer,
1054 {
1055 match self {
1056 Self::Null => serializer.serialize_unit(),
1057 Self::Bool(value) => serializer.serialize_bool(*value),
1058 Self::Number(value) => value.serialize(serializer),
1059 Self::String(value) => serializer.serialize_str(value),
1060 Self::Array(values) => values.serialize(serializer),
1061 Self::Object(value) => value.serialize(serializer),
1062 }
1063 }
1064}
1065
1066impl<'de> Deserialize<'de> for OrderedJsonValue {
1067 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1068 where
1069 D: Deserializer<'de>,
1070 {
1071 struct OrderedValueVisitor;
1072
1073 impl<'de> Visitor<'de> for OrderedValueVisitor {
1074 type Value = OrderedJsonValue;
1075
1076 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1077 formatter.write_str("a JSON value with ordered object members")
1078 }
1079
1080 fn visit_unit<E>(self) -> Result<Self::Value, E>
1081 where
1082 E: serde::de::Error,
1083 {
1084 Ok(OrderedJsonValue::Null)
1085 }
1086
1087 fn visit_none<E>(self) -> Result<Self::Value, E>
1088 where
1089 E: serde::de::Error,
1090 {
1091 Ok(OrderedJsonValue::Null)
1092 }
1093
1094 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1095 where
1096 D: Deserializer<'de>,
1097 {
1098 OrderedJsonValue::deserialize(deserializer)
1099 }
1100
1101 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1102 where
1103 E: serde::de::Error,
1104 {
1105 Ok(OrderedJsonValue::Bool(value))
1106 }
1107
1108 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1109 where
1110 E: serde::de::Error,
1111 {
1112 Ok(OrderedJsonValue::Number(value.into()))
1113 }
1114
1115 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1116 where
1117 E: serde::de::Error,
1118 {
1119 Ok(OrderedJsonValue::Number(value.into()))
1120 }
1121
1122 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1123 where
1124 E: serde::de::Error,
1125 {
1126 serde_json::Number::from_f64(value)
1127 .map(OrderedJsonValue::Number)
1128 .ok_or_else(|| E::custom("non-finite JSON number"))
1129 }
1130
1131 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1132 where
1133 E: serde::de::Error,
1134 {
1135 Ok(OrderedJsonValue::String(value.to_owned()))
1136 }
1137
1138 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1139 where
1140 E: serde::de::Error,
1141 {
1142 Ok(OrderedJsonValue::String(value))
1143 }
1144
1145 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1146 where
1147 A: SeqAccess<'de>,
1148 {
1149 let mut values = Vec::new();
1150 while let Some(value) = sequence.next_element()? {
1151 values.push(value);
1152 }
1153 Ok(OrderedJsonValue::Array(values))
1154 }
1155
1156 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1157 where
1158 A: MapAccess<'de>,
1159 {
1160 let mut entries = Vec::new();
1161 while let Some((key, value)) = map.next_entry()? {
1162 entries.push((key, value));
1163 }
1164 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1165 }
1166 }
1167
1168 deserializer.deserialize_any(OrderedValueVisitor)
1169 }
1170}
1171
1172impl Serialize for OrderedJsonObject {
1173 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1174 where
1175 S: Serializer,
1176 {
1177 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1178 for (key, value) in &self.0 {
1179 map.serialize_entry(key, value)?;
1180 }
1181 map.end()
1182 }
1183}
1184
1185impl<'de> Deserialize<'de> for OrderedJsonObject {
1186 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1187 where
1188 D: Deserializer<'de>,
1189 {
1190 struct OrderedObjectVisitor;
1191
1192 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1193 type Value = OrderedJsonObject;
1194
1195 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1196 formatter.write_str("an object with ordered JSON members")
1197 }
1198
1199 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1200 where
1201 A: MapAccess<'de>,
1202 {
1203 let mut entries = Vec::new();
1204 while let Some((key, value)) = map.next_entry()? {
1205 entries.push((key, value));
1206 }
1207 Ok(OrderedJsonObject(entries))
1208 }
1209 }
1210
1211 deserializer.deserialize_map(OrderedObjectVisitor)
1212 }
1213}
1214
1215fn read_tagged<'de, D>(
1216 deserializer: D,
1217 field: &'static str,
1218) -> Result<(String, OrderedJsonObject), D::Error>
1219where
1220 D: Deserializer<'de>,
1221{
1222 let body = OrderedJsonObject::deserialize(deserializer)?;
1223 let mut tag = None;
1224 for (key, value) in body.as_entries() {
1225 if key != field {
1226 continue;
1227 }
1228 if tag.is_some() {
1229 return Err(D::Error::custom(format!(
1230 "tagged object has duplicate `{field}` field"
1231 )));
1232 }
1233 let OrderedJsonValue::String(value) = value else {
1234 return Err(D::Error::custom(format!(
1235 "tagged object has no string `{field}` field"
1236 )));
1237 };
1238 tag = Some(value);
1239 }
1240 let Some(tag) = tag else {
1241 return Err(D::Error::custom(format!(
1242 "tagged object has no string `{field}` field"
1243 )));
1244 };
1245 Ok((tag.to_string(), body))
1246}
1247
1248fn read_ordered_tagged(
1249 value: OrderedJsonValue,
1250 field: &'static str,
1251) -> Result<(String, OrderedJsonObject), String> {
1252 let OrderedJsonValue::Object(body) = value else {
1253 return Err(format!("expected tagged object with `{field}` field"));
1254 };
1255 let mut tag = None;
1256 for (key, value) in body.as_entries() {
1257 if key != field {
1258 continue;
1259 }
1260 if tag.is_some() {
1261 return Err(format!("tagged object has duplicate `{field}` field"));
1262 }
1263 let OrderedJsonValue::String(value) = value else {
1264 return Err(format!("tagged object has no string `{field}` field"));
1265 };
1266 tag = Some(value);
1267 }
1268 let Some(tag) = tag else {
1269 return Err(format!("tagged object has no string `{field}` field"));
1270 };
1271 Ok((tag.to_string(), body))
1272}
1273
1274fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1275 body.as_entries()
1276 .iter()
1277 .find_map(|(key, value)| (key == field).then_some(value))
1278}
1279
1280fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1281 match ordered_field(body, field) {
1282 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1283 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1284 None => Err(format!("tagged object has no `{field}` field")),
1285 }
1286}
1287
1288fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1289 let (tag, body) = read_ordered_tagged(value, "method")?;
1290 match tag.as_str() {
1291 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1292 digest: ordered_string(&body, "digest")?,
1293 }),
1294 "macos_spawn_inode" => {
1295 let device = ordered_field(&body, "device")
1296 .and_then(|value| match value {
1297 OrderedJsonValue::Number(number) => number.as_u64(),
1298 _ => None,
1299 })
1300 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1301 let inode = ordered_field(&body, "inode")
1302 .and_then(|value| match value {
1303 OrderedJsonValue::Number(number) => number.as_u64(),
1304 _ => None,
1305 })
1306 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1307 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1308 }
1309 "windows_spawn_file_id" => {
1310 let wire: RunningImageEvidenceWire = serde_json::from_value(
1311 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1312 )
1313 .map_err(|error| error.to_string())?;
1314 match wire {
1315 RunningImageEvidenceWire::WindowsSpawnFileId {
1316 volume_serial_number,
1317 file_id,
1318 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1319 volume_serial_number,
1320 file_id,
1321 }),
1322 _ => unreachable!(),
1323 }
1324 }
1325 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1326 }
1327}
1328
1329impl Serialize for ModuleDeclaredProvenance {
1330 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1331 where
1332 S: Serializer,
1333 {
1334 match self {
1335 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1336 build: build.clone(),
1337 }
1338 .serialize(serializer),
1339 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1340 Self::Unknown { body, .. } => body.serialize(serializer),
1341 }
1342 }
1343}
1344
1345impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1346 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1347 where
1348 D: serde::Deserializer<'de>,
1349 {
1350 let (tag, value) = read_tagged(deserializer, "status")?;
1351 match tag.as_str() {
1352 "reported" => match serde_json::from_value(value.into_value())
1353 .map_err(D::Error::custom)?
1354 {
1355 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1356 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1357 },
1358 "unverifiable" => {
1359 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1360 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1361 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1362 }
1363 }
1364 _ => Ok(Self::Unknown { tag, body: value }),
1365 }
1366 }
1367}
1368
1369impl Serialize for RunningImageAgreement {
1370 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1371 where
1372 S: Serializer,
1373 {
1374 match self {
1375 Self::Match { evidence } => RunningImageAgreementWire::Match {
1376 evidence: evidence.clone(),
1377 }
1378 .serialize(serializer),
1379 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1380 running: running.clone(),
1381 disk: disk.clone(),
1382 }
1383 .serialize(serializer),
1384 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1385 reason: reason.clone(),
1386 }
1387 .serialize(serializer),
1388 Self::Unknown { body, .. } => body.serialize(serializer),
1389 }
1390 }
1391}
1392
1393impl Serialize for ReloadPathAgreement {
1394 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1395 where
1396 S: Serializer,
1397 {
1398 match self {
1399 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1400 Self::Mismatch {
1401 configured,
1402 spawned_from,
1403 } => ReloadPathAgreementWire::Mismatch {
1404 configured: configured.clone(),
1405 spawned_from: spawned_from.clone(),
1406 }
1407 .serialize(serializer),
1408 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1409 reason: reason.clone(),
1410 }
1411 .serialize(serializer),
1412 Self::Unknown { body, .. } => body.serialize(serializer),
1413 }
1414 }
1415}
1416
1417impl Serialize for LaunchSpecAgreement {
1418 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1419 where
1420 S: Serializer,
1421 {
1422 match self {
1423 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1424 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1425 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1426 reason: reason.clone(),
1427 }
1428 .serialize(serializer),
1429 Self::Unknown { body, .. } => body.serialize(serializer),
1430 }
1431 }
1432}
1433
1434impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1435 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1436 where
1437 D: Deserializer<'de>,
1438 {
1439 let (tag, body) = read_tagged(deserializer, "status")?;
1440 match tag.as_str() {
1441 "match" => Ok(Self::Match),
1442 "mismatch" => Ok(Self::Mismatch),
1443 "unavailable" => match serde_json::from_value(body.into_value())
1444 .map_err(D::Error::custom)?
1445 {
1446 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1447 _ => unreachable!(),
1448 },
1449 _ => Ok(Self::Unknown { tag, body }),
1450 }
1451 }
1452}
1453
1454impl<'de> Deserialize<'de> for ReloadPathAgreement {
1455 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1456 where
1457 D: Deserializer<'de>,
1458 {
1459 let (tag, body) = read_tagged(deserializer, "status")?;
1460 match tag.as_str() {
1461 "match" => Ok(Self::Match),
1462 "mismatch" => {
1463 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1464 ReloadPathAgreementWire::Mismatch {
1465 configured,
1466 spawned_from,
1467 } => Ok(Self::Mismatch {
1468 configured,
1469 spawned_from,
1470 }),
1471 _ => unreachable!(),
1472 }
1473 }
1474 "unavailable" => match serde_json::from_value(body.into_value())
1475 .map_err(D::Error::custom)?
1476 {
1477 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1478 _ => unreachable!(),
1479 },
1480 _ => Ok(Self::Unknown { tag, body }),
1481 }
1482 }
1483}
1484
1485impl<'de> Deserialize<'de> for RunningImageAgreement {
1486 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1487 where
1488 D: serde::Deserializer<'de>,
1489 {
1490 let (tag, value) = read_tagged(deserializer, "status")?;
1491 match tag.as_str() {
1492 "match" => Ok(Self::Match {
1493 evidence: decode_running_image_evidence(
1494 ordered_field(&value, "evidence")
1495 .cloned()
1496 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1497 )
1498 .map_err(D::Error::custom)?,
1499 }),
1500 "mismatch" => Ok(Self::Mismatch {
1501 running: decode_running_image_evidence(
1502 ordered_field(&value, "running")
1503 .cloned()
1504 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1505 )
1506 .map_err(D::Error::custom)?,
1507 disk: decode_running_image_evidence(
1508 ordered_field(&value, "disk")
1509 .cloned()
1510 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1511 )
1512 .map_err(D::Error::custom)?,
1513 }),
1514 "unavailable" => Ok(Self::Unavailable {
1515 reason: serde_json::from_value(
1516 ordered_field(&value, "reason")
1517 .cloned()
1518 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1519 .into_value(),
1520 )
1521 .map_err(D::Error::custom)?,
1522 }),
1523 _ => Ok(Self::Unknown { tag, body: value }),
1524 }
1525 }
1526}
1527
1528impl Serialize for ChildResourceUsage {
1529 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1530 where
1531 S: Serializer,
1532 {
1533 match self {
1534 Self::Measured(reading) => {
1535 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1536 }
1537 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1538 reason: reason.clone(),
1539 }
1540 .serialize(serializer),
1541 Self::Unknown { body, .. } => body.serialize(serializer),
1542 }
1543 }
1544}
1545
1546impl<'de> Deserialize<'de> for ChildResourceUsage {
1547 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1548 where
1549 D: Deserializer<'de>,
1550 {
1551 let (tag, body) = read_tagged(deserializer, "status")?;
1552 match tag.as_str() {
1553 "measured" | "unavailable" => {
1554 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1555 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1556 ChildResourceUsageWire::Unavailable { reason } => {
1557 Ok(Self::Unavailable { reason })
1558 }
1559 }
1560 }
1561 _ => Ok(Self::Unknown { tag, body }),
1562 }
1563 }
1564}
1565
1566impl Serialize for RunningImageEvidence {
1567 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1568 where
1569 S: Serializer,
1570 {
1571 match self {
1572 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1573 digest: digest.clone(),
1574 }
1575 .serialize(serializer),
1576 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1577 device: *device,
1578 inode: *inode,
1579 }
1580 .serialize(serializer),
1581 Self::WindowsSpawnFileId {
1582 volume_serial_number,
1583 file_id,
1584 } => RunningImageEvidenceWire::WindowsSpawnFileId {
1585 volume_serial_number: *volume_serial_number,
1586 file_id: *file_id,
1587 }
1588 .serialize(serializer),
1589 Self::Unknown { body, .. } => body.serialize(serializer),
1590 }
1591 }
1592}
1593
1594impl<'de> Deserialize<'de> for RunningImageEvidence {
1595 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1596 where
1597 D: serde::Deserializer<'de>,
1598 {
1599 let (tag, value) = read_tagged(deserializer, "method")?;
1600 match tag.as_str() {
1601 "linux_proc_sha256" => {
1602 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1603 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1604 Ok(Self::LinuxProcSha256 { digest })
1605 }
1606 _ => unreachable!(),
1607 }
1608 }
1609 "macos_spawn_inode" => {
1610 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1611 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1612 Ok(Self::MacosSpawnInode { device, inode })
1613 }
1614 _ => unreachable!(),
1615 }
1616 }
1617 "windows_spawn_file_id" => {
1618 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1619 RunningImageEvidenceWire::WindowsSpawnFileId {
1620 volume_serial_number,
1621 file_id,
1622 } => Ok(Self::WindowsSpawnFileId {
1623 volume_serial_number,
1624 file_id,
1625 }),
1626 _ => unreachable!(),
1627 }
1628 }
1629 _ => Ok(Self::Unknown { tag, body: value }),
1630 }
1631 }
1632}
1633
1634impl Serialize for SupervisorRouteConsumer {
1635 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1636 where
1637 S: Serializer,
1638 {
1639 match self {
1640 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1641 module_id: module_id.clone(),
1642 }
1643 .serialize(serializer),
1644 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1645 connection_id: *connection_id,
1646 }
1647 .serialize(serializer),
1648 Self::Unknown { body, .. } => body.serialize(serializer),
1649 }
1650 }
1651}
1652
1653impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1654 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1655 where
1656 D: serde::Deserializer<'de>,
1657 {
1658 let (tag, value) = read_tagged(deserializer, "kind")?;
1659 match tag.as_str() {
1660 "reserved" => {
1661 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1662 SupervisorRouteConsumerWire::Reserved { module_id } => {
1663 Ok(Self::Reserved { module_id })
1664 }
1665 _ => unreachable!(),
1666 }
1667 }
1668 "direct" => {
1669 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1670 SupervisorRouteConsumerWire::Direct { connection_id } => {
1671 Ok(Self::Direct { connection_id })
1672 }
1673 _ => unreachable!(),
1674 }
1675 }
1676 _ => Ok(Self::Unknown { tag, body: value }),
1677 }
1678 }
1679}
1680
1681impl Serialize for StderrCaptureState {
1682 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1683 where
1684 S: Serializer,
1685 {
1686 match self {
1687 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1688 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1689 reason: reason.clone(),
1690 }
1691 .serialize(serializer),
1692 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1693 reason: reason.clone(),
1694 }
1695 .serialize(serializer),
1696 Self::Unknown { body, .. } => body.serialize(serializer),
1697 }
1698 }
1699}
1700
1701impl<'de> Deserialize<'de> for StderrCaptureState {
1702 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1703 where
1704 D: serde::Deserializer<'de>,
1705 {
1706 let (tag, value) = read_tagged(deserializer, "state")?;
1707 match tag.as_str() {
1708 "captured" => {
1709 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1710 StderrCaptureStateWire::Captured => Ok(Self::Captured),
1711 _ => unreachable!(),
1712 }
1713 }
1714 "incomplete" => match serde_json::from_value(value.into_value())
1715 .map_err(D::Error::custom)?
1716 {
1717 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1718 _ => unreachable!(),
1719 },
1720 "not_captured" => match serde_json::from_value(value.into_value())
1721 .map_err(D::Error::custom)?
1722 {
1723 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1724 _ => unreachable!(),
1725 },
1726 _ => Ok(Self::Unknown { tag, body: value }),
1727 }
1728 }
1729}
1730
1731impl Serialize for StderrTailEntry {
1732 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1733 where
1734 S: Serializer,
1735 {
1736 match self {
1737 Self::Line {
1738 text,
1739 truncated,
1740 at_ms,
1741 } => StderrTailEntryWire::Line {
1742 text: text.clone(),
1743 truncated: *truncated,
1744 at_ms: *at_ms,
1745 }
1746 .serialize(serializer),
1747 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1748 Self::Unknown { body, .. } => body.serialize(serializer),
1749 }
1750 }
1751}
1752
1753impl<'de> Deserialize<'de> for StderrTailEntry {
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, "kind")?;
1759 match tag.as_str() {
1760 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1761 StderrTailEntryWire::Line {
1762 text,
1763 truncated,
1764 at_ms,
1765 } => Ok(Self::Line {
1766 text,
1767 truncated,
1768 at_ms,
1769 }),
1770 _ => unreachable!(),
1771 },
1772 "process_start" => {
1773 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1774 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1775 _ => unreachable!(),
1776 }
1777 }
1778 _ => Ok(Self::Unknown { tag, body: value }),
1779 }
1780 }
1781}
1782
1783fn is_zero_u64(value: &u64) -> bool {
1784 *value == 0
1785}
1786
1787fn default_true() -> bool {
1788 true
1789}
1790
1791#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1793pub struct TerminalHistory {
1794 pub daemon_started_at_ms: u64,
1796 pub entries: Vec<TerminalEntry>,
1797 #[serde(default, skip_serializing_if = "is_zero_u64")]
1800 pub dropped: u64,
1801 #[serde(default, skip_serializing_if = "is_zero_u64")]
1804 pub journal_skipped_lines: u64,
1805 #[serde(default, skip_serializing_if = "is_zero_u64")]
1807 pub journal_read_errors: u64,
1808 #[serde(default, skip_serializing_if = "is_zero_u64")]
1810 pub journal_write_failures: u64,
1811}
1812
1813#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1815pub struct TerminalEntry {
1816 #[serde(default, skip_serializing_if = "Option::is_none")]
1819 pub daemon_incarnation: Option<String>,
1820 #[serde(default, skip_serializing_if = "Option::is_none")]
1821 pub exit_code: Option<i32>,
1822 #[serde(default, skip_serializing_if = "Option::is_none")]
1823 pub exit_signal: Option<i32>,
1824 pub at_ms: u64,
1825 pub disposition: TerminalDisposition,
1826 #[serde(default, skip_serializing_if = "Option::is_none")]
1830 pub exit_kind: Option<TerminalExitKind>,
1831 #[serde(default, skip_serializing_if = "Option::is_none")]
1838 pub disposition_detail: Option<String>,
1839}
1840
1841#[derive(Debug, Clone, PartialEq, Eq)]
1846pub enum TerminalExitKind {
1847 Clean,
1848 Crash,
1849 DeliberateSeverance,
1850 Unknown(String),
1851}
1852
1853impl TerminalExitKind {
1854 fn wire_name(&self) -> &str {
1855 match self {
1856 Self::Clean => "clean",
1857 Self::Crash => "crash",
1858 Self::DeliberateSeverance => "deliberate_severance",
1859 Self::Unknown(value) => value,
1860 }
1861 }
1862}
1863
1864impl Serialize for TerminalExitKind {
1865 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1866 where
1867 S: serde::Serializer,
1868 {
1869 serializer.serialize_str(self.wire_name())
1870 }
1871}
1872
1873impl<'de> Deserialize<'de> for TerminalExitKind {
1874 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1875 where
1876 D: serde::Deserializer<'de>,
1877 {
1878 let value = String::deserialize(deserializer)?;
1879 Ok(match value.as_str() {
1880 "clean" => Self::Clean,
1881 "crash" => Self::Crash,
1882 "deliberate_severance" => Self::DeliberateSeverance,
1883 _ => Self::Unknown(value),
1884 })
1885 }
1886}
1887
1888open_string_enum! {
1889 TerminalDisposition {
1891 Stopped => "stopped",
1892 Disabled => "disabled",
1893 Failed => "failed",
1894 Restarting => "restarting",
1895 DaemonShutdown => "daemon_shutdown",
1900 }
1901}
1902
1903#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1904#[serde(rename_all = "snake_case")]
1905pub enum PollKind {
1906 Status,
1907 Liveness,
1908}
1909
1910#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1922#[non_exhaustive]
1923pub struct CatalogEntry {
1924 pub module_id: String,
1925 #[serde(default = "default_true")]
1936 pub ready: bool,
1937 #[serde(default, skip_serializing_if = "Option::is_none")]
1941 pub not_ready: Option<NotReadyReason>,
1942 #[serde(default, skip_serializing_if = "Option::is_none")]
1963 pub module_version: Option<String>,
1964 pub roles: Vec<ProviderRole>,
1965 pub control_ops: Vec<String>,
1966 #[serde(default, skip_serializing_if = "Option::is_none")]
1971 pub capabilities: Option<CapabilityDeclarations>,
1972 #[serde(default, skip_serializing_if = "Option::is_none")]
1975 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
1976 #[serde(default, skip_serializing_if = "Option::is_none")]
1980 pub events: Option<Vec<EventDeclaration>>,
1981 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1984 pub operation_delivery: BTreeMap<String, OperationDelivery>,
1985}
1986
1987impl CatalogEntry {
1988 #[must_use]
1990 pub fn new(
1991 module_id: impl Into<String>,
1992 roles: Vec<ProviderRole>,
1993 control_ops: Vec<String>,
1994 ) -> Self {
1995 Self {
1996 module_id: module_id.into(),
1997 ready: default_true(),
1998 not_ready: None,
1999 module_version: None,
2000 roles,
2001 control_ops,
2002 capabilities: None,
2003 self_signals: None,
2004 events: None,
2005 operation_delivery: BTreeMap::new(),
2006 }
2007 }
2008
2009 #[must_use]
2011 pub fn with_ready(mut self, ready: bool) -> Self {
2012 self.ready = ready;
2013 self
2014 }
2015
2016 #[must_use]
2018 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2019 self.not_ready = not_ready;
2020 self
2021 }
2022
2023 #[must_use]
2025 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2026 self.module_version = module_version;
2027 self
2028 }
2029
2030 #[must_use]
2032 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2033 self.capabilities = capabilities;
2034 self
2035 }
2036
2037 #[must_use]
2039 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2040 self.self_signals = self_signals;
2041 self
2042 }
2043
2044 #[must_use]
2046 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2047 self.events = events;
2048 self
2049 }
2050
2051 #[must_use]
2054 pub fn with_operation_delivery(
2055 mut self,
2056 operation_delivery: BTreeMap<String, OperationDelivery>,
2057 ) -> Self {
2058 self.operation_delivery = operation_delivery;
2059 self
2060 }
2061}
2062
2063#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2065pub struct NotReadyReason {
2066 pub reason: String,
2071 #[serde(default, skip_serializing_if = "Option::is_none")]
2074 pub capability: Option<String>,
2075}
2076
2077impl NotReadyReason {
2078 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2079 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2080}
2081
2082#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2083pub struct CapabilityRequirementStatus {
2084 pub consumer: String,
2085 pub capability: String,
2086 pub need: String,
2087 pub verdict: String,
2088 pub episode_seq: u64,
2089 pub config_satisfiable: bool,
2090 pub runtime_available: bool,
2091 pub detail: String,
2092}
2093
2094#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2095pub struct SupervisorRescanResult {
2096 pub added: Vec<String>,
2097 pub removed: Vec<String>,
2098 pub changed_pending_reload: Vec<String>,
2099 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2112 pub enabled_changes: Vec<String>,
2113 pub unchanged: u32,
2114 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2122 pub preview: bool,
2123 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2141 pub restart_required: Vec<String>,
2142 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2146 pub capability_warnings: Vec<String>,
2147}
2148
2149#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2165#[serde(rename_all = "snake_case")]
2166pub enum ModuleProtocol {
2167 #[default]
2171 Subc,
2172 None,
2181}
2182
2183#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2195#[non_exhaustive]
2196pub struct SupervisorEntry {
2197 #[serde(default, skip_serializing_if = "Option::is_none")]
2200 pub waiting_for_previous_pid: Option<u32>,
2201 pub module_id: String,
2202 pub state: String,
2203 pub enabled: bool,
2204 pub live: bool,
2214 #[serde(default)]
2218 pub protocol: ModuleProtocol,
2219 #[serde(default, skip_serializing_if = "Option::is_none")]
2222 pub launch_nonce_env: Option<bool>,
2223 #[serde(default, skip_serializing_if = "Option::is_none")]
2229 pub launch_nonce_source: Option<String>,
2230 pub health: SupervisorHealthStatus,
2231 #[serde(default, skip_serializing_if = "Option::is_none")]
2234 pub pending_reload: Option<PendingReloadVerdict>,
2235 #[serde(default)]
2241 pub last_probe_ms: Option<u64>,
2242 #[serde(default, skip_serializing_if = "Option::is_none")]
2246 pub last_exit_code: Option<i32>,
2247 #[serde(default, skip_serializing_if = "Option::is_none")]
2251 pub last_exit_signal: Option<i32>,
2252 #[serde(default, skip_serializing_if = "Option::is_none")]
2256 pub last_exit_ms: Option<u64>,
2257 #[serde(default, skip_serializing_if = "Option::is_none")]
2260 pub last_exit_kind: Option<TerminalExitKind>,
2261 #[serde(default, skip_serializing_if = "Option::is_none")]
2278 pub restart_count: Option<u32>,
2279 #[serde(default, skip_serializing_if = "Option::is_none")]
2282 pub max_restarts: Option<u32>,
2283 #[serde(default, skip_serializing_if = "Option::is_none")]
2286 pub lifetime_restarts: Option<u32>,
2287 #[serde(default, skip_serializing_if = "Option::is_none")]
2291 pub spawn_generation: Option<u64>,
2292 #[serde(default, skip_serializing_if = "Option::is_none")]
2302 pub restart_window_secs: Option<u64>,
2303 #[serde(default, skip_serializing_if = "Option::is_none")]
2307 pub drain_timeout_ms: Option<u64>,
2308 #[serde(default, skip_serializing_if = "Option::is_none")]
2311 pub restart_backoff_ms: Option<u64>,
2312 #[serde(default, skip_serializing_if = "Option::is_none")]
2315 pub restart_max_backoff_ms: Option<u64>,
2316 #[serde(default, skip_serializing_if = "Option::is_none")]
2329 pub resources: Option<ChildResourceUsage>,
2330}
2331
2332impl SupervisorEntry {
2333 #[must_use]
2335 pub fn new(
2336 module_id: impl Into<String>,
2337 state: impl Into<String>,
2338 enabled: bool,
2339 live: bool,
2340 health: SupervisorHealthStatus,
2341 ) -> Self {
2342 Self {
2343 module_id: module_id.into(),
2344 state: state.into(),
2345 waiting_for_previous_pid: None,
2346 enabled,
2347 live,
2348 protocol: ModuleProtocol::default(),
2349 launch_nonce_env: None,
2350 launch_nonce_source: None,
2351 health,
2352 pending_reload: None,
2353 last_probe_ms: None,
2354 last_exit_code: None,
2355 last_exit_signal: None,
2356 last_exit_ms: None,
2357 last_exit_kind: None,
2358 restart_count: None,
2359 max_restarts: None,
2360 lifetime_restarts: None,
2361 spawn_generation: None,
2362 restart_window_secs: None,
2363 drain_timeout_ms: None,
2364 restart_backoff_ms: None,
2365 restart_max_backoff_ms: None,
2366 resources: None,
2367 }
2368 }
2369
2370 #[must_use]
2372 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2373 self.protocol = protocol;
2374 self
2375 }
2376
2377 #[must_use]
2379 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2380 self.launch_nonce_env = launch_nonce_env;
2381 self
2382 }
2383
2384 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2385 self.launch_nonce_source = source;
2386 self
2387 }
2388
2389 #[must_use]
2390 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2391 self.waiting_for_previous_pid = pid;
2392 self
2393 }
2394
2395 #[must_use]
2397 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2398 self.pending_reload = pending_reload;
2399 self
2400 }
2401
2402 #[must_use]
2404 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2405 self.last_probe_ms = last_probe_ms;
2406 self
2407 }
2408
2409 #[must_use]
2411 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2412 self.last_exit_code = last_exit_code;
2413 self
2414 }
2415
2416 #[must_use]
2418 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2419 self.last_exit_signal = last_exit_signal;
2420 self
2421 }
2422
2423 #[must_use]
2425 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2426 self.last_exit_ms = last_exit_ms;
2427 self
2428 }
2429
2430 #[must_use]
2432 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2433 self.last_exit_kind = last_exit_kind;
2434 self
2435 }
2436
2437 #[must_use]
2439 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2440 self.restart_count = restart_count;
2441 self
2442 }
2443
2444 #[must_use]
2446 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2447 self.max_restarts = max_restarts;
2448 self
2449 }
2450
2451 #[must_use]
2453 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2454 self.lifetime_restarts = lifetime_restarts;
2455 self
2456 }
2457
2458 #[must_use]
2460 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2461 self.spawn_generation = spawn_generation;
2462 self
2463 }
2464
2465 #[must_use]
2467 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2468 self.restart_window_secs = restart_window_secs;
2469 self
2470 }
2471
2472 #[must_use]
2474 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2475 self.drain_timeout_ms = drain_timeout_ms;
2476 self
2477 }
2478
2479 #[must_use]
2481 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2482 self.restart_backoff_ms = restart_backoff_ms;
2483 self
2484 }
2485
2486 #[must_use]
2488 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2489 self.restart_max_backoff_ms = restart_max_backoff_ms;
2490 self
2491 }
2492
2493 #[must_use]
2495 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2496 self.resources = resources;
2497 self
2498 }
2499}
2500
2501#[derive(Debug, Clone, PartialEq)]
2504pub enum ChildResourceUsage {
2505 Measured(ChildResourceReading),
2506 Unavailable {
2507 reason: ChildResourceUnavailableReason,
2508 },
2509 Unknown {
2512 tag: String,
2513 body: OrderedJsonObject,
2514 },
2515}
2516
2517#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2519pub struct ChildResourceReading {
2520 pub memory_bytes: u64,
2523 pub memory_kind: ChildMemoryKind,
2524 #[serde(default, skip_serializing_if = "Option::is_none")]
2527 pub swap_bytes: Option<u64>,
2528 pub cpu_user_ms: u64,
2532 pub cpu_system_ms: u64,
2535}
2536
2537open_string_enum! {
2538 ChildMemoryKind {
2540 PhysFootprint => "phys_footprint",
2544 ResidentSet => "resident_set",
2547 WindowsWorkingSet => "windows_working_set",
2550 }
2551}
2552
2553open_string_enum! {
2554 ChildResourceUnavailableReason {
2556 NotRunning => "not_running",
2558 UnsupportedPlatform => "unsupported_platform",
2560 Unreadable => "unreadable",
2563 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2566 }
2567}
2568
2569#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2570#[serde(rename_all = "snake_case")]
2571pub enum SupervisorHealthStatus {
2572 Ok,
2573 Degraded,
2574 Failing,
2575 Unresponsive,
2576 Unknown,
2577}
2578
2579#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2580pub struct SupervisorHealthEntry {
2581 pub module_id: String,
2582 pub status: SupervisorHealthStatus,
2583 #[serde(default, skip_serializing_if = "Option::is_none")]
2589 pub detail: Option<String>,
2590 #[serde(default, skip_serializing_if = "Option::is_none")]
2595 pub metrics: Option<serde_json::Value>,
2596 pub consecutive_failures: u32,
2597 #[serde(default)]
2600 pub late_answer_count: u64,
2601 #[serde(default, skip_serializing_if = "Option::is_none")]
2603 pub last_late_answer_latency_ms: Option<u64>,
2604 #[serde(default)]
2609 pub last_action: Option<String>,
2610 #[serde(default)]
2613 pub last_action_ms: Option<u64>,
2614 #[serde(default, skip_serializing_if = "Option::is_none")]
2627 pub last_probe_ms: Option<u64>,
2628}
2629
2630#[cfg(test)]
2631mod tests {
2632 #[test]
2633 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2634 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2635 volume_serial_number: u64::MAX,
2636 file_id: [
2637 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2638 ],
2639 };
2640 let agreement = super::RunningImageAgreement::Match { evidence };
2641 let encoded = serde_json::to_string(&agreement).unwrap();
2642 assert!(encoded.contains("windows_spawn_file_id"));
2643 assert_eq!(
2644 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
2645 agreement
2646 );
2647 }
2648
2649 #[test]
2650 fn unix_running_image_evidence_keeps_original_wire_bytes() {
2651 assert_eq!(
2652 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
2653 device: 7,
2654 inode: 11
2655 })
2656 .unwrap(),
2657 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
2658 );
2659 assert_eq!(
2660 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
2661 digest: "abc".to_owned()
2662 })
2663 .unwrap(),
2664 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
2665 );
2666 }
2667 use super::*;
2668 use subc_protocol::{BindIdentity, RouteTarget};
2669
2670 #[test]
2671 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2672 let entry = TerminalEntry {
2673 daemon_incarnation: Some("daemon-before-restart".into()),
2674 exit_code: Some(1),
2675 exit_signal: None,
2676 at_ms: 1_700_000_000_123,
2677 disposition: TerminalDisposition::Restarting,
2678 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2679 disposition_detail: None,
2680 };
2681 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2682 assert_eq!(
2683 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2684 ["exit_kind"],
2685 "deliberate_severance"
2686 );
2687
2688 #[derive(serde::Deserialize)]
2689 struct LegacyTerminalEntry {
2690 exit_code: Option<i32>,
2691 exit_signal: Option<i32>,
2692 at_ms: u64,
2693 disposition: TerminalDisposition,
2694 }
2695
2696 let decoded: LegacyTerminalEntry =
2697 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2698 assert_eq!(decoded.exit_code, Some(1));
2699 assert_eq!(decoded.exit_signal, None);
2700 assert_eq!(decoded.at_ms, 1_700_000_000_123);
2701 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
2702
2703 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
2704 let future: TerminalEntry =
2705 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
2706 assert_eq!(
2707 future.exit_kind,
2708 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
2709 );
2710 }
2711
2712 #[test]
2713 fn terminal_incarnation_is_optional_for_older_daemons() {
2714 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
2715 "at_ms": 123,
2716 "disposition": "stopped"
2717 }))
2718 .unwrap();
2719 let encoded = serde_json::to_value(&entry).unwrap();
2720 assert_eq!(
2721 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
2722 (None, None)
2723 );
2724 }
2725
2726 #[test]
2727 fn route_poll_uses_kind_field() {
2728 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
2729 route_channel: 7,
2730 route_epoch: 11,
2731 kind: PollKind::Status,
2732 })
2733 .unwrap();
2734
2735 assert_eq!(body["op"], "route.poll");
2736 assert_eq!(body["route_epoch"], 11);
2737 assert_eq!(body["kind"], "status");
2738 assert!(body.get("op").is_some());
2739 }
2740
2741 #[test]
2742 fn route_open_is_internally_tagged() {
2743 let request = ClientControlRequest::RouteOpen {
2744 target: RouteTarget::ToolProvider {
2745 module_id: "aft".to_string(),
2746 },
2747 identity: BindIdentity::new("/tmp/project", "opencode", "session-1"),
2748 consumer_identity: None,
2749 consumer_capabilities: None,
2750 role_versions: None,
2751 admission_facts: None,
2752 scope: None,
2753 };
2754
2755 let body = serde_json::to_value(request).unwrap();
2756 assert_eq!(body["op"], "route.open");
2757 assert_eq!(body["target"]["kind"], "tool_provider");
2758 assert!(body.get("consumer_identity").is_none());
2759 assert!(body.get("consumer_capabilities").is_none());
2760 assert!(body.get("role_versions").is_none());
2761 }
2762
2763 #[test]
2764 fn route_open_without_optional_fields_still_decodes() {
2765 let body = serde_json::json!({
2766 "op": "route.open",
2767 "target": { "kind": "tool_provider", "module_id": "aft" },
2768 "identity": {
2769 "project_root": "/tmp/project",
2770 "harness": "opencode",
2771 "session": "session-1"
2772 }
2773 });
2774
2775 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
2776 let ClientControlRequest::RouteOpen {
2777 consumer_identity,
2778 consumer_capabilities,
2779 role_versions,
2780 admission_facts,
2781 ..
2782 } = decoded
2783 else {
2784 panic!("decoded wrong request variant");
2785 };
2786 assert_eq!(consumer_identity, None);
2787 assert_eq!(consumer_capabilities, None);
2788 assert_eq!(role_versions, None);
2789 assert_eq!(admission_facts, None);
2790 }
2791
2792 #[test]
2793 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
2794 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
2795 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
2796 match decoded {
2797 ClientControlPush::RouteClosed {
2798 excluded_subscriptions,
2799 terminal,
2800 ..
2801 } => {
2802 assert_eq!(excluded_subscriptions, 0);
2803 assert_eq!(terminal, None);
2804 }
2805 other => panic!("unexpected push: {other:?}"),
2806 }
2807 assert!(!serde_json::to_string(&decoded)
2808 .unwrap()
2809 .contains("terminal"));
2810 }
2811
2812 #[test]
2813 fn old_route_closed_decoder_ignores_new_terminal_field() {
2814 #[derive(serde::Deserialize)]
2815 #[serde(tag = "op")]
2816 enum LegacyClientControlPush {
2817 #[serde(rename = "route.closed")]
2818 RouteClosed {
2819 module_id: String,
2820 reason: RouteCloseReason,
2821 drained: bool,
2822 abandoned: u32,
2823 },
2824 }
2825
2826 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
2827 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
2828 match decoded {
2829 LegacyClientControlPush::RouteClosed {
2830 module_id,
2831 reason,
2832 drained,
2833 abandoned,
2834 } => {
2835 assert_eq!(module_id, "aft-tools");
2836 assert_eq!(reason, RouteCloseReason::Crash);
2837 assert!(!drained);
2838 assert_eq!(abandoned, 0);
2839 }
2840 }
2841 }
2842
2843 #[test]
2844 fn supervisor_routes_is_a_control_plane_request() {
2845 let body = serde_json::json!({
2846 "op": "supervisor.routes",
2847 "module_id": "aft"
2848 });
2849
2850 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
2851 assert_eq!(serde_json::to_value(request).unwrap(), body);
2852 }
2853
2854 #[test]
2855 fn diagnostic_string_enums_retain_unknown_wire_values() {
2856 let reason: RunningImageUnavailableReason =
2857 serde_json::from_str("\"future_reason\"").unwrap();
2858 let disposition: TerminalDisposition =
2859 serde_json::from_str("\"future_disposition\"").unwrap();
2860
2861 assert_eq!(
2862 reason,
2863 RunningImageUnavailableReason::Unknown("future_reason".to_string())
2864 );
2865 assert_eq!(
2866 disposition,
2867 TerminalDisposition::Unknown("future_disposition".to_string())
2868 );
2869 }
2870
2871 #[test]
2872 fn diagnostic_string_enums_preserve_existing_wire_names() {
2873 let names = [
2874 (RunningImageUnavailableReason::NotRunning, "not_running"),
2875 (
2876 RunningImageUnavailableReason::UnsupportedPlatform,
2877 "unsupported_platform",
2878 ),
2879 (
2880 RunningImageUnavailableReason::RunningExecutableUnreadable,
2881 "running_executable_unreadable",
2882 ),
2883 (
2884 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
2885 "running_executable_permission_denied",
2886 ),
2887 (
2888 RunningImageUnavailableReason::ProcessHidden,
2889 "process_hidden",
2890 ),
2891 (
2892 RunningImageUnavailableReason::SpawnedPathUnreadable,
2893 "spawned_path_unreadable",
2894 ),
2895 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
2896 (
2897 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
2898 "process_identity_unconfirmed",
2899 ),
2900 ];
2901 for (value, expected) in names {
2902 let wire = serde_json::to_string(&value).unwrap();
2903 assert_eq!(wire, format!("\"{expected}\""));
2904 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
2905 assert_eq!(decoded, value);
2906 }
2907
2908 for (value, expected) in [
2909 (TerminalDisposition::Stopped, "stopped"),
2910 (TerminalDisposition::Disabled, "disabled"),
2911 (TerminalDisposition::Failed, "failed"),
2912 (TerminalDisposition::Restarting, "restarting"),
2913 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
2914 ] {
2915 let wire = serde_json::to_string(&value).unwrap();
2916 assert_eq!(wire, format!("\"{expected}\""));
2917 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
2918 assert_eq!(decoded, value);
2919 }
2920 }
2921
2922 #[test]
2923 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
2924 let entry = SupervisorEntry::new(
2925 "waiting-module",
2926 "starting",
2927 true,
2928 false,
2929 SupervisorHealthStatus::Unknown,
2930 );
2931 let old_wire = serde_json::to_value(&entry).unwrap();
2932 assert!(old_wire.get("waiting_for_previous_pid").is_none());
2933 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
2934 assert_eq!(decoded.waiting_for_previous_pid, None);
2935 let entry = entry.with_waiting_for_previous_pid(Some(42));
2936 let wire = serde_json::to_value(&entry).unwrap();
2937 assert_eq!(wire["waiting_for_previous_pid"], 42);
2938 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
2939 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
2940 }
2941
2942 #[test]
2943 fn diagnostic_string_enums_reject_non_string_bodies() {
2944 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
2945 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
2946 }
2947
2948 #[test]
2949 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
2950 let body = serde_json::json!({
2951 "op": "supervisor.provenance",
2952 "daemon": {
2953 "daemon_build": {},
2954 "daemon_observed": {
2955 "running_image": {
2956 "status": "unavailable",
2957 "reason": "not_running"
2958 }
2959 }
2960 },
2961 "modules": [
2962 {
2963 "module_id": "future",
2964 "module_declared": { "status": "unverifiable" },
2965 "daemon_observed": {
2966 "running_image": {
2967 "status": "unavailable",
2968 "reason": "future_reason"
2969 }
2970 }
2971 },
2972 {
2973 "module_id": "healthy-a",
2974 "module_declared": { "status": "unverifiable" },
2975 "daemon_observed": {
2976 "running_image": {
2977 "status": "match",
2978 "evidence": {
2979 "method": "linux_proc_sha256",
2980 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
2981 }
2982 }
2983 }
2984 },
2985 {
2986 "module_id": "healthy-b",
2987 "module_declared": { "status": "unverifiable" },
2988 "daemon_observed": {
2989 "running_image": {
2990 "status": "unavailable",
2991 "reason": "unsupported_platform"
2992 }
2993 }
2994 }
2995 ]
2996 });
2997
2998 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
2999 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3000 panic!("decoded wrong response variant");
3001 };
3002 assert_eq!(modules.len(), 3);
3003 assert_eq!(modules[0].module_id, "future");
3004 assert_eq!(
3005 modules[0].daemon_observed.running_image,
3006 RunningImageAgreement::Unavailable {
3007 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3008 }
3009 );
3010 assert_eq!(modules[1].module_id, "healthy-a");
3011 assert_eq!(modules[2].module_id, "healthy-b");
3012 }
3013
3014 #[test]
3015 fn tagged_unknown_values_retain_tag_and_body() {
3016 macro_rules! assert_unknown_round_trip {
3017 ($ty:ident, $field:literal, $value:expr) => {
3018 let value = $value;
3019 let wire = serde_json::to_string(&value).unwrap();
3020 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3021 match decoded {
3022 $ty::Unknown { tag, body } => {
3023 assert_eq!(tag, value[$field].as_str().unwrap());
3024 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3025 }
3026 _ => panic!("decoded known variant"),
3027 }
3028 };
3029 }
3030
3031 assert_unknown_round_trip!(
3032 ModuleDeclaredProvenance,
3033 "status",
3034 serde_json::json!({"status": "future", "build": {"version": 7}})
3035 );
3036 assert_unknown_round_trip!(
3037 RunningImageAgreement,
3038 "status",
3039 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3040 );
3041 assert_unknown_round_trip!(
3042 RunningImageEvidence,
3043 "method",
3044 serde_json::json!({"method": "future", "digest": "abc"})
3045 );
3046 assert_unknown_round_trip!(
3047 SupervisorRouteConsumer,
3048 "kind",
3049 serde_json::json!({"kind": "future", "module_id": "m"})
3050 );
3051 assert_unknown_round_trip!(
3052 StderrCaptureState,
3053 "state",
3054 serde_json::json!({"state": "future", "reason": "because"})
3055 );
3056 assert_unknown_round_trip!(
3057 StderrTailEntry,
3058 "kind",
3059 serde_json::json!({"kind": "future", "text": "line"})
3060 );
3061 assert_unknown_round_trip!(
3062 ChildResourceUsage,
3063 "status",
3064 serde_json::json!({"status": "future", "memory_bytes": 1})
3065 );
3066 }
3067
3068 #[test]
3069 fn child_resource_usage_round_trips_both_known_states() {
3070 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3071 memory_bytes: 0,
3072 memory_kind: ChildMemoryKind::ResidentSet,
3073 swap_bytes: Some(0),
3074 cpu_user_ms: 0,
3075 cpu_system_ms: 0,
3076 });
3077 let wire = serde_json::to_value(&measured).unwrap();
3078 assert_eq!(
3079 wire,
3080 serde_json::json!({
3081 "status": "measured",
3082 "memory_bytes": 0,
3083 "memory_kind": "resident_set",
3084 "swap_bytes": 0,
3085 "cpu_user_ms": 0,
3086 "cpu_system_ms": 0
3087 })
3088 );
3089 assert_eq!(
3090 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3091 measured
3092 );
3093
3094 let unavailable = ChildResourceUsage::Unavailable {
3095 reason: ChildResourceUnavailableReason::NotRunning,
3096 };
3097 let wire = serde_json::to_value(&unavailable).unwrap();
3098 assert_eq!(
3099 wire,
3100 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3101 );
3102 assert_eq!(
3103 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3104 unavailable
3105 );
3106 }
3107
3108 #[test]
3109 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3110 let stamped: StderrTailEntry = serde_json::from_str(
3114 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3115 )
3116 .unwrap();
3117 assert_eq!(
3118 stamped,
3119 StderrTailEntry::Line {
3120 text: "boom".to_string(),
3121 truncated: true,
3122 at_ms: Some(1_789_801_440_685),
3123 }
3124 );
3125 let unstamped: StderrTailEntry =
3126 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3127 assert_eq!(
3128 unstamped,
3129 StderrTailEntry::Line {
3130 text: "boom".to_string(),
3131 truncated: false,
3132 at_ms: None,
3133 }
3134 );
3135 assert_eq!(
3138 serde_json::to_string(&unstamped).unwrap(),
3139 r#"{"kind":"line","text":"boom"}"#
3140 );
3141 assert_eq!(
3142 serde_json::to_value(&stamped).unwrap()["at_ms"],
3143 serde_json::json!(1_789_801_440_685u64)
3144 );
3145 }
3146
3147 #[test]
3148 fn tagged_unknown_values_round_trip_the_original_json() {
3149 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3150 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3151 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3152 }
3153
3154 #[test]
3155 fn tagged_unknown_values_round_trip_trailing_tag() {
3156 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3157 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3158 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3159
3160 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3161 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3162 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3163 }
3164
3165 #[test]
3166 fn tagged_unknown_values_round_trip_middle_tag() {
3167 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3168 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3169 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3170
3171 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3172 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3173 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3174 }
3175
3176 #[test]
3177 fn tagged_unknown_values_round_trip_deep_payload() {
3178 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3179 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3180 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3181
3182 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3183 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3184 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3185 }
3186
3187 #[test]
3188 fn tagged_unknown_values_reject_non_object_bodies() {
3189 for wire in ["42", r#""future""#, "[]"] {
3190 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3191 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3192 }
3193 }
3194
3195 #[test]
3196 fn duplicate_discriminators_reject_without_panicking() {
3197 assert_eq!(
3198 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3199 .unwrap(),
3200 ModuleDeclaredProvenance::Unverifiable
3201 );
3202 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3203 .unwrap()
3204 {
3205 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3206 _ => panic!("future discriminator decoded as a known variant"),
3207 }
3208
3209 let wires = [
3210 r#"{"status":"reported","status":"unverifiable"}"#,
3211 r#"{"status":"unverifiable","status":"reported"}"#,
3212 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3213 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3214 ];
3215
3216 for wire in wires {
3217 let result =
3218 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3219 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3220 assert!(
3221 result.unwrap().is_err(),
3222 "duplicate discriminator decoded: {wire}"
3223 );
3224 }
3225
3226 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3227 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3228 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3229 assert!(
3230 result.unwrap().is_err(),
3231 "duplicate discriminator decoded: {wire}"
3232 );
3233 }
3234
3235 #[test]
3236 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3237 let known_wire =
3238 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3239 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3240 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3241
3242 for wire in [
3243 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3244 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3245 ] {
3246 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3247 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3248 }
3249
3250 for wire in [
3251 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3252 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3253 ] {
3254 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3255 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3256 }
3257
3258 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3259 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3260 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3261
3262 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3263 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3264 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3265 }
3266
3267 #[test]
3268 fn tagged_unknown_member_does_not_discard_known_siblings() {
3269 let body = serde_json::json!({
3270 "modules": [{
3271 "module_id": "target",
3272 "routes": [
3273 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3274 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3275 ]
3276 }]
3277 });
3278 let decoded: ClientControlResponse = serde_json::from_value(
3279 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3280 )
3281 .unwrap();
3282 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3283 panic!("decoded wrong response variant");
3284 };
3285 assert_eq!(modules[0].routes.len(), 2);
3286 assert_eq!(
3287 modules[0].routes[1].consumer,
3288 SupervisorRouteConsumer::Direct { connection_id: 7 }
3289 );
3290 }
3291}
3292
3293#[cfg(test)]
3294mod launch_nonce_redaction_tests {
3295 use super::*;
3296
3297 const NONCE: &str = "nonce-f00dfeed1234abcd";
3298
3299 fn identity() -> ConsumerIdentity {
3300 ConsumerIdentity {
3301 module_id: "wernicke".to_string(),
3302 launch_nonce: NONCE.to_string(),
3303 }
3304 }
3305
3306 #[test]
3307 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3308 let printed = format!("{:?}", identity());
3309 assert!(printed.contains("wernicke"), "{printed}");
3310 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3311 }
3312
3313 #[test]
3314 fn route_open_request_debug_never_prints_the_nonce() {
3315 let request = ClientControlRequest::RouteOpen {
3316 target: subc_protocol::RouteTarget::ToolProvider {
3317 module_id: "broca".to_string(),
3318 },
3319 identity: subc_protocol::BindIdentity::new(
3320 PathBuf::from("/tmp/project"),
3321 "test".to_string(),
3322 "session".to_string(),
3323 ),
3324 consumer_identity: Some(identity()),
3325 consumer_capabilities: None,
3326 role_versions: None,
3327 admission_facts: None,
3328 scope: None,
3329 };
3330 let printed = format!("{request:?}");
3331 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3332 }
3333}