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