1#![forbid(unsafe_code)]
9
10use std::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::{CapabilityDeclarations, ManifestProvenance, ProviderRole, SelfSignalDeclaration},
19 scope::ScopeSelector,
20 session::HealthStatus,
21 BindIdentity, RouteTarget,
22};
23
24pub use subc_protocol::RouteCloseReason;
25
26macro_rules! open_string_enum {
27 (
28 $(#[$meta:meta])*
29 $name:ident {
30 $( $(#[$variant_meta:meta])* $variant:ident => $wire_name:literal ),+ $(,)?
31 }
32 ) => {
33 $(#[$meta])*
34 #[derive(Debug, Clone, PartialEq, Eq)]
35 pub enum $name {
36 $( $(#[$variant_meta])* $variant, )+
37 Unknown(String),
38 }
39
40 impl $name {
41 fn wire_name(&self) -> &str {
42 match self {
43 $( Self::$variant => $wire_name, )+
44 Self::Unknown(value) => value,
45 }
46 }
47 }
48
49 impl Serialize for $name {
50 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
51 where
52 S: serde::Serializer,
53 {
54 serializer.serialize_str(self.wire_name())
55 }
56 }
57
58 impl<'de> Deserialize<'de> for $name {
59 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
60 where
61 D: serde::Deserializer<'de>,
62 {
63 let value = String::deserialize(deserializer)?;
64 Ok(match value.as_str() {
65 $( $wire_name => Self::$variant, )+
66 _ => Self::Unknown(value),
67 })
68 }
69 }
70 };
71}
72
73#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
75pub struct ConsumerIdentity {
76 pub module_id: String,
77 pub launch_nonce: String,
78}
79
80impl std::fmt::Debug for ConsumerIdentity {
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 f.debug_struct("ConsumerIdentity")
87 .field("module_id", &self.module_id)
88 .field(
89 "launch_nonce",
90 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
91 )
92 .finish()
93 }
94}
95
96pub mod ops {
107 pub const SERVER: &str = "server.";
108 pub const CATALOG: &str = "catalog.";
109 pub const ROUTE: &str = "route.";
110 pub const SUPERVISOR: &str = "supervisor.";
111 pub const CONFIG: &str = "config.";
112
113 pub const SERVER_DESCRIBE: &str = "server.describe";
114 pub const CATALOG_LIST: &str = "catalog.list";
115 pub const ROUTE_OPEN: &str = "route.open";
116 pub const ROUTE_POLL: &str = "route.poll";
117 pub const ROUTE_CLOSING: &str = "route.closing";
118 pub const ROUTE_CLOSED: &str = "route.closed";
119 pub const SUPERVISOR_LIST: &str = "supervisor.list";
120 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
121 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
122 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
123 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
124 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
125 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
126 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
127 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
128 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
129 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
130 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
131 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
132 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
133 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
138#[serde(tag = "op")]
139#[allow(clippy::large_enum_variant)]
142pub enum ClientControlRequest {
143 #[serde(rename = "server.describe")]
144 ServerDescribe {},
145 #[serde(rename = "catalog.list")]
146 CatalogList {
147 #[serde(default)]
152 module_id: Option<String>,
153 },
154 #[serde(rename = "route.open")]
155 RouteOpen {
156 target: RouteTarget,
157 identity: BindIdentity,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
167 consumer_identity: Option<ConsumerIdentity>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
176 consumer_capabilities: Option<Vec<String>>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
179 admission_facts: Option<serde_json::Value>,
180 #[serde(default, skip_serializing_if = "Option::is_none")]
187 scope: Option<ScopeSelector>,
188 },
189 #[serde(rename = "route.poll")]
190 RoutePoll {
191 route_channel: u16,
192 route_epoch: u32,
193 kind: PollKind,
194 },
195 #[serde(rename = "supervisor.list")]
196 SupervisorList {},
197 #[serde(rename = "supervisor.spawn_snapshot")]
199 SupervisorSpawnSnapshot {},
200 #[serde(rename = "supervisor.spawn_subscribe")]
216 SupervisorSpawnSubscribe {
217 #[serde(default, skip_serializing_if = "Option::is_none")]
218 since: Option<SpawnCursor>,
219 },
220 #[serde(rename = "supervisor.restart")]
221 SupervisorRestart {
222 module_id: String,
223 #[serde(default, skip_serializing_if = "Option::is_none")]
231 drain_timeout_ms: Option<u64>,
232 },
233 #[serde(rename = "supervisor.swap")]
248 SupervisorSwap {
249 module_id: String,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
253 ready_timeout_ms: Option<u64>,
254 },
255 #[serde(rename = "supervisor.reload")]
256 SupervisorReload { module_id: String },
257 #[serde(rename = "supervisor.rescan")]
258 SupervisorRescan {
259 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
279 preview: bool,
280 },
281 #[serde(rename = "supervisor.release_reserved")]
285 SupervisorReleaseReserved { module_id: String },
286 #[serde(rename = "supervisor.set_enabled")]
287 SupervisorSetEnabled { module_id: String, enabled: bool },
288 #[serde(rename = "supervisor.health_probe")]
289 SupervisorHealthProbe { module_id: String },
290 #[serde(rename = "supervisor.health")]
291 SupervisorHealth {},
292 #[serde(rename = "supervisor.routes")]
305 SupervisorRoutes {
306 #[serde(default, skip_serializing_if = "Option::is_none")]
307 module_id: Option<String>,
308 },
309 #[serde(rename = "supervisor.provenance")]
312 SupervisorProvenance {
313 #[serde(default, skip_serializing_if = "Option::is_none")]
314 module_id: Option<String>,
315 },
316 #[serde(rename = "supervisor.stderr_tail")]
324 SupervisorStderrTail {
325 module_id: String,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
327 max_lines: Option<u32>,
328 #[serde(default, skip_serializing_if = "Option::is_none")]
329 max_bytes: Option<u32>,
330 },
331 #[serde(rename = "supervisor.terminals")]
344 SupervisorTerminals { module_id: String },
345}
346
347#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
349#[serde(tag = "op")]
350pub enum ClientControlResponse {
351 #[serde(rename = "server.describe")]
352 ServerDescribe {
353 protocol_ver: u8,
354 subc_ops: Vec<String>,
355 capabilities: Vec<String>,
356 connected_clients: u64,
357 #[serde(default, skip_serializing_if = "Option::is_none")]
358 counters: Option<serde_json::Value>,
359 #[serde(default, skip_serializing_if = "Option::is_none")]
366 build_git_sha: Option<String>,
367 #[serde(default, skip_serializing_if = "Option::is_none")]
373 build_lock_digest: Option<String>,
374 #[serde(default, skip_serializing_if = "Vec::is_empty")]
378 capability_requirements: Vec<CapabilityRequirementStatus>,
379 #[serde(default, skip_serializing_if = "Option::is_none")]
384 machine_id: Option<String>,
385 },
386 #[serde(rename = "catalog.list")]
387 CatalogList {
388 generation: u64,
389 modules: Vec<CatalogEntry>,
390 subc_ops: Vec<String>,
391 },
392 #[serde(rename = "route.open")]
393 RouteOpen {
394 route_channel: u16,
395 route_epoch: u32,
396 },
397 #[serde(rename = "route.poll")]
398 RoutePoll {
399 route_channel: u16,
400 route_epoch: u32,
401 status: Option<String>,
402 live: Option<bool>,
403 },
404 #[serde(rename = "supervisor.list")]
405 SupervisorList {
406 generation: u64,
407 modules: Vec<SupervisorEntry>,
408 },
409 #[serde(rename = "supervisor.spawn_snapshot")]
410 SupervisorSpawnSnapshot {
411 #[serde(flatten)]
412 snapshot: SpawnSnapshot,
413 },
414 #[serde(rename = "supervisor.ack")]
415 SupervisorAck { module_id: String, applied: bool },
416 #[serde(rename = "supervisor.rescan")]
417 SupervisorRescan {
418 #[serde(flatten)]
419 result: SupervisorRescanResult,
420 },
421 #[serde(rename = "supervisor.health_probe")]
422 SupervisorHealthProbe {
423 module_id: String,
424 status: HealthStatus,
425 #[serde(default, skip_serializing_if = "Option::is_none")]
426 detail: Option<String>,
427 #[serde(default, skip_serializing_if = "Option::is_none")]
428 metrics: Option<serde_json::Value>,
429 },
430 #[serde(rename = "supervisor.health")]
431 SupervisorHealth {
432 generation: u64,
433 modules: Vec<SupervisorHealthEntry>,
434 },
435 #[serde(rename = "supervisor.routes")]
436 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
437 #[serde(rename = "supervisor.provenance")]
438 SupervisorProvenance {
439 daemon: SupervisorDaemonProvenance,
440 modules: Vec<SupervisorModuleProvenance>,
441 },
442 #[serde(rename = "supervisor.stderr_tail")]
443 SupervisorStderrTail {
444 module_id: String,
445 #[serde(flatten)]
446 tail: StderrTail,
447 },
448 #[serde(rename = "supervisor.terminals")]
449 SupervisorTerminals {
450 module_id: String,
451 #[serde(flatten)]
452 terminals: TerminalHistory,
453 },
454}
455
456#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
461#[serde(tag = "op")]
462pub enum ClientControlPush {
463 #[serde(rename = "route.closing")]
464 RouteClosing {
465 module_id: String,
466 reason: RouteCloseReason,
467 },
468 #[serde(rename = "route.closed")]
469 RouteClosed {
470 module_id: String,
471 reason: RouteCloseReason,
472 drained: bool,
474 abandoned: u32,
477 #[serde(default)]
479 excluded_subscriptions: u32,
480 #[serde(default, skip_serializing_if = "Option::is_none")]
486 terminal: Option<bool>,
487 },
488}
489
490#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
492pub struct SpawnCursor {
493 pub daemon_incarnation: String,
494 pub seq: u64,
495}
496
497#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
499pub struct LiveSpawn {
500 pub module_id: String,
501 pub spawn_generation: u64,
502 pub pid: u32,
503 pub spawned_at_ms: u64,
504}
505
506#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
508pub struct SpawnSnapshot {
509 pub cursor: SpawnCursor,
510 pub ring_bound: u64,
512 pub live: Vec<LiveSpawn>,
513}
514
515#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
517#[serde(rename_all = "snake_case")]
518pub enum SpawnEventKind {
519 Spawned,
520 Exited,
521}
522
523#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
529pub struct SpawnEvent {
530 pub cursor: SpawnCursor,
531 pub kind: SpawnEventKind,
532 pub module_id: String,
533 pub spawn_generation: u64,
534 pub pid: u32,
535 #[serde(default, skip_serializing_if = "Option::is_none")]
536 pub exit_code: Option<i32>,
537 #[serde(default, skip_serializing_if = "Option::is_none")]
538 pub exit_signal: Option<i32>,
539}
540
541#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
543pub struct StderrTail {
544 pub capture: StderrCaptureState,
545 pub entries: Vec<StderrTailEntry>,
546 #[serde(default, skip_serializing_if = "is_zero_u64")]
555 pub dropped_lines: u64,
556}
557
558#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
560pub struct SupervisorRouteModule {
561 pub module_id: String,
562 pub routes: Vec<SupervisorRoute>,
563}
564
565#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
567pub struct SupervisorRoute {
568 pub consumer: SupervisorRouteConsumer,
569 pub age_ms: u64,
571 pub draining: bool,
574 #[serde(default, skip_serializing_if = "Option::is_none")]
580 pub drain_reason: Option<RouteCloseReason>,
581}
582
583#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
585pub struct SupervisorModuleProvenance {
586 pub module_id: String,
587 pub module_declared: ModuleDeclaredProvenance,
588 pub daemon_observed: SupervisorObservedProcess,
589}
590
591#[derive(Debug, Clone, PartialEq)]
593pub enum ModuleDeclaredProvenance {
594 Reported {
595 build: ManifestProvenance,
596 },
597 Unverifiable,
598 Unknown {
601 tag: String,
602 body: OrderedJsonObject,
603 },
604}
605
606#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
611pub struct SupervisorObservedProcess {
612 #[serde(default, skip_serializing_if = "Option::is_none")]
613 pub pid: Option<u32>,
614 #[serde(default, skip_serializing_if = "Option::is_none")]
615 pub spawned_at_ms: Option<u64>,
616 #[serde(default, skip_serializing_if = "Option::is_none")]
617 pub spawned_from: Option<PathBuf>,
618 pub running_image: RunningImageAgreement,
619}
620
621#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
624pub struct PendingReloadVerdict {
625 pub path: ReloadPathAgreement,
626 pub image: RunningImageAgreement,
627}
628
629#[derive(Debug, Clone, PartialEq)]
631pub enum ReloadPathAgreement {
632 Match,
633 Mismatch {
634 configured: PathBuf,
635 spawned_from: PathBuf,
636 },
637 Unavailable {
638 reason: ReloadPathUnavailableReason,
639 },
640 Unknown {
641 tag: String,
642 body: OrderedJsonObject,
643 },
644}
645
646open_string_enum! {
647 ReloadPathUnavailableReason {
649 NotRunning => "not_running",
650 SpawnedPathUnavailable => "spawned_path_unavailable",
651 }
652}
653
654#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
656pub struct SupervisorDaemonProvenance {
657 pub daemon_build: DaemonBuildProvenance,
658 pub daemon_observed: DaemonObservedProcess,
659}
660
661#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
663pub struct DaemonBuildProvenance {
664 #[serde(default, skip_serializing_if = "Option::is_none")]
665 pub build_git_sha: Option<String>,
666 #[serde(default, skip_serializing_if = "Option::is_none")]
667 pub build_lock_digest: Option<String>,
668}
669
670#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
672pub struct DaemonObservedProcess {
673 #[serde(default, skip_serializing_if = "Option::is_none")]
674 pub pid: Option<u32>,
675 #[serde(default, skip_serializing_if = "Option::is_none")]
680 pub started_at_ms: Option<u64>,
681 pub running_image: RunningImageAgreement,
682}
683
684#[derive(Debug, Clone, PartialEq)]
686pub enum RunningImageAgreement {
687 Match {
688 evidence: RunningImageEvidence,
689 },
690 Mismatch {
691 running: RunningImageEvidence,
692 disk: RunningImageEvidence,
693 },
694 Unavailable {
695 reason: RunningImageUnavailableReason,
696 },
697 Unknown {
700 tag: String,
701 body: OrderedJsonObject,
702 },
703}
704
705#[derive(Debug, Clone, PartialEq)]
707pub enum RunningImageEvidence {
708 LinuxProcSha256 {
709 digest: String,
710 },
711 MacosSpawnInode {
712 device: u64,
713 inode: u64,
714 },
715 Unknown {
718 tag: String,
719 body: OrderedJsonObject,
720 },
721}
722
723open_string_enum! {
724 RunningImageUnavailableReason {
726 NotRunning => "not_running",
727 UnsupportedPlatform => "unsupported_platform",
728 RunningExecutableUnreadable => "running_executable_unreadable",
729 SpawnedPathUnreadable => "spawned_path_unreadable",
730 HashFailed => "hash_failed",
731 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
732 }
733}
734
735#[derive(Debug, Clone, PartialEq)]
741pub enum SupervisorRouteConsumer {
742 Reserved {
743 module_id: String,
744 },
745 Direct {
746 connection_id: u64,
747 },
748 Unknown {
751 tag: String,
752 body: OrderedJsonObject,
753 },
754}
755
756#[derive(Debug, Clone, PartialEq)]
763pub enum StderrCaptureState {
764 Captured,
767 Incomplete { reason: String },
769 NotCaptured { reason: String },
771 Unknown {
774 tag: String,
775 body: OrderedJsonObject,
776 },
777}
778
779#[derive(Debug, Clone, PartialEq)]
780pub enum StderrTailEntry {
781 Line {
782 text: String,
783 truncated: bool,
788 at_ms: Option<u64>,
792 },
793 ProcessStart,
798 Unknown {
801 tag: String,
802 body: OrderedJsonObject,
803 },
804}
805
806#[derive(Debug, Serialize, Deserialize)]
807#[serde(tag = "status", rename_all = "snake_case")]
808enum ModuleDeclaredProvenanceWire {
809 Reported { build: ManifestProvenance },
810 Unverifiable,
811}
812
813#[derive(Debug, Serialize, Deserialize)]
814#[serde(tag = "status", rename_all = "snake_case")]
815enum RunningImageAgreementWire {
816 Match {
817 evidence: RunningImageEvidence,
818 },
819 Mismatch {
820 running: RunningImageEvidence,
821 disk: RunningImageEvidence,
822 },
823 Unavailable {
824 reason: RunningImageUnavailableReason,
825 },
826}
827
828#[derive(Debug, Serialize, Deserialize)]
829#[serde(tag = "status", rename_all = "snake_case")]
830enum ReloadPathAgreementWire {
831 Match,
832 Mismatch {
833 configured: PathBuf,
834 spawned_from: PathBuf,
835 },
836 Unavailable {
837 reason: ReloadPathUnavailableReason,
838 },
839}
840
841#[derive(Debug, Serialize, Deserialize)]
842#[serde(tag = "method", rename_all = "snake_case")]
843enum RunningImageEvidenceWire {
844 LinuxProcSha256 { digest: String },
845 MacosSpawnInode { device: u64, inode: u64 },
846}
847
848#[derive(Debug, Serialize, Deserialize)]
849#[serde(tag = "kind", rename_all = "snake_case")]
850enum SupervisorRouteConsumerWire {
851 Reserved { module_id: String },
852 Direct { connection_id: u64 },
853}
854
855#[derive(Debug, Serialize, Deserialize)]
856#[serde(tag = "state", rename_all = "snake_case")]
857enum StderrCaptureStateWire {
858 Captured,
859 Incomplete { reason: String },
860 NotCaptured { reason: String },
861}
862
863#[derive(Debug, Serialize, Deserialize)]
864#[serde(tag = "status", rename_all = "snake_case")]
865enum ChildResourceUsageWire {
866 Measured(ChildResourceReading),
867 Unavailable {
868 reason: ChildResourceUnavailableReason,
869 },
870}
871
872#[derive(Debug, Serialize, Deserialize)]
873#[serde(tag = "kind", rename_all = "snake_case")]
874enum StderrTailEntryWire {
875 Line {
876 text: String,
877 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
878 truncated: bool,
879 #[serde(default, skip_serializing_if = "Option::is_none")]
882 at_ms: Option<u64>,
883 },
884 ProcessStart,
885}
886
887#[derive(Debug, Clone, PartialEq)]
889pub enum OrderedJsonValue {
890 Null,
891 Bool(bool),
892 Number(serde_json::Number),
893 String(String),
894 Array(Vec<Self>),
895 Object(OrderedJsonObject),
896}
897
898#[derive(Debug, Clone, PartialEq)]
900pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
901
902impl OrderedJsonObject {
903 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
905 &self.0
906 }
907
908 fn into_value(self) -> serde_json::Value {
909 serde_json::Value::Object(
910 self.0
911 .into_iter()
912 .map(|(key, value)| (key, value.into_value()))
913 .collect(),
914 )
915 }
916}
917
918impl OrderedJsonValue {
919 fn into_value(self) -> serde_json::Value {
920 match self {
921 Self::Null => serde_json::Value::Null,
922 Self::Bool(value) => serde_json::Value::Bool(value),
923 Self::Number(value) => serde_json::Value::Number(value),
924 Self::String(value) => serde_json::Value::String(value),
925 Self::Array(values) => {
926 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
927 }
928 Self::Object(value) => value.into_value(),
929 }
930 }
931}
932
933impl Serialize for OrderedJsonValue {
934 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
935 where
936 S: Serializer,
937 {
938 match self {
939 Self::Null => serializer.serialize_unit(),
940 Self::Bool(value) => serializer.serialize_bool(*value),
941 Self::Number(value) => value.serialize(serializer),
942 Self::String(value) => serializer.serialize_str(value),
943 Self::Array(values) => values.serialize(serializer),
944 Self::Object(value) => value.serialize(serializer),
945 }
946 }
947}
948
949impl<'de> Deserialize<'de> for OrderedJsonValue {
950 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
951 where
952 D: Deserializer<'de>,
953 {
954 struct OrderedValueVisitor;
955
956 impl<'de> Visitor<'de> for OrderedValueVisitor {
957 type Value = OrderedJsonValue;
958
959 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
960 formatter.write_str("a JSON value with ordered object members")
961 }
962
963 fn visit_unit<E>(self) -> Result<Self::Value, E>
964 where
965 E: serde::de::Error,
966 {
967 Ok(OrderedJsonValue::Null)
968 }
969
970 fn visit_none<E>(self) -> Result<Self::Value, E>
971 where
972 E: serde::de::Error,
973 {
974 Ok(OrderedJsonValue::Null)
975 }
976
977 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
978 where
979 D: Deserializer<'de>,
980 {
981 OrderedJsonValue::deserialize(deserializer)
982 }
983
984 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
985 where
986 E: serde::de::Error,
987 {
988 Ok(OrderedJsonValue::Bool(value))
989 }
990
991 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
992 where
993 E: serde::de::Error,
994 {
995 Ok(OrderedJsonValue::Number(value.into()))
996 }
997
998 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
999 where
1000 E: serde::de::Error,
1001 {
1002 Ok(OrderedJsonValue::Number(value.into()))
1003 }
1004
1005 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1006 where
1007 E: serde::de::Error,
1008 {
1009 serde_json::Number::from_f64(value)
1010 .map(OrderedJsonValue::Number)
1011 .ok_or_else(|| E::custom("non-finite JSON number"))
1012 }
1013
1014 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1015 where
1016 E: serde::de::Error,
1017 {
1018 Ok(OrderedJsonValue::String(value.to_owned()))
1019 }
1020
1021 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1022 where
1023 E: serde::de::Error,
1024 {
1025 Ok(OrderedJsonValue::String(value))
1026 }
1027
1028 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1029 where
1030 A: SeqAccess<'de>,
1031 {
1032 let mut values = Vec::new();
1033 while let Some(value) = sequence.next_element()? {
1034 values.push(value);
1035 }
1036 Ok(OrderedJsonValue::Array(values))
1037 }
1038
1039 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1040 where
1041 A: MapAccess<'de>,
1042 {
1043 let mut entries = Vec::new();
1044 while let Some((key, value)) = map.next_entry()? {
1045 entries.push((key, value));
1046 }
1047 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1048 }
1049 }
1050
1051 deserializer.deserialize_any(OrderedValueVisitor)
1052 }
1053}
1054
1055impl Serialize for OrderedJsonObject {
1056 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1057 where
1058 S: Serializer,
1059 {
1060 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1061 for (key, value) in &self.0 {
1062 map.serialize_entry(key, value)?;
1063 }
1064 map.end()
1065 }
1066}
1067
1068impl<'de> Deserialize<'de> for OrderedJsonObject {
1069 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1070 where
1071 D: Deserializer<'de>,
1072 {
1073 struct OrderedObjectVisitor;
1074
1075 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1076 type Value = OrderedJsonObject;
1077
1078 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1079 formatter.write_str("an object with ordered JSON members")
1080 }
1081
1082 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1083 where
1084 A: MapAccess<'de>,
1085 {
1086 let mut entries = Vec::new();
1087 while let Some((key, value)) = map.next_entry()? {
1088 entries.push((key, value));
1089 }
1090 Ok(OrderedJsonObject(entries))
1091 }
1092 }
1093
1094 deserializer.deserialize_map(OrderedObjectVisitor)
1095 }
1096}
1097
1098fn read_tagged<'de, D>(
1099 deserializer: D,
1100 field: &'static str,
1101) -> Result<(String, OrderedJsonObject), D::Error>
1102where
1103 D: Deserializer<'de>,
1104{
1105 let body = OrderedJsonObject::deserialize(deserializer)?;
1106 let mut tag = None;
1107 for (key, value) in body.as_entries() {
1108 if key != field {
1109 continue;
1110 }
1111 if tag.is_some() {
1112 return Err(D::Error::custom(format!(
1113 "tagged object has duplicate `{field}` field"
1114 )));
1115 }
1116 let OrderedJsonValue::String(value) = value else {
1117 return Err(D::Error::custom(format!(
1118 "tagged object has no string `{field}` field"
1119 )));
1120 };
1121 tag = Some(value);
1122 }
1123 let Some(tag) = tag else {
1124 return Err(D::Error::custom(format!(
1125 "tagged object has no string `{field}` field"
1126 )));
1127 };
1128 Ok((tag.to_string(), body))
1129}
1130
1131fn read_ordered_tagged(
1132 value: OrderedJsonValue,
1133 field: &'static str,
1134) -> Result<(String, OrderedJsonObject), String> {
1135 let OrderedJsonValue::Object(body) = value else {
1136 return Err(format!("expected tagged object with `{field}` field"));
1137 };
1138 let mut tag = None;
1139 for (key, value) in body.as_entries() {
1140 if key != field {
1141 continue;
1142 }
1143 if tag.is_some() {
1144 return Err(format!("tagged object has duplicate `{field}` field"));
1145 }
1146 let OrderedJsonValue::String(value) = value else {
1147 return Err(format!("tagged object has no string `{field}` field"));
1148 };
1149 tag = Some(value);
1150 }
1151 let Some(tag) = tag else {
1152 return Err(format!("tagged object has no string `{field}` field"));
1153 };
1154 Ok((tag.to_string(), body))
1155}
1156
1157fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1158 body.as_entries()
1159 .iter()
1160 .find_map(|(key, value)| (key == field).then_some(value))
1161}
1162
1163fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1164 match ordered_field(body, field) {
1165 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1166 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1167 None => Err(format!("tagged object has no `{field}` field")),
1168 }
1169}
1170
1171fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1172 let (tag, body) = read_ordered_tagged(value, "method")?;
1173 match tag.as_str() {
1174 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1175 digest: ordered_string(&body, "digest")?,
1176 }),
1177 "macos_spawn_inode" => {
1178 let device = ordered_field(&body, "device")
1179 .and_then(|value| match value {
1180 OrderedJsonValue::Number(number) => number.as_u64(),
1181 _ => None,
1182 })
1183 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1184 let inode = ordered_field(&body, "inode")
1185 .and_then(|value| match value {
1186 OrderedJsonValue::Number(number) => number.as_u64(),
1187 _ => None,
1188 })
1189 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1190 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1191 }
1192 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1193 }
1194}
1195
1196impl Serialize for ModuleDeclaredProvenance {
1197 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1198 where
1199 S: Serializer,
1200 {
1201 match self {
1202 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1203 build: build.clone(),
1204 }
1205 .serialize(serializer),
1206 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1207 Self::Unknown { body, .. } => body.serialize(serializer),
1208 }
1209 }
1210}
1211
1212impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1213 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1214 where
1215 D: serde::Deserializer<'de>,
1216 {
1217 let (tag, value) = read_tagged(deserializer, "status")?;
1218 match tag.as_str() {
1219 "reported" => match serde_json::from_value(value.into_value())
1220 .map_err(D::Error::custom)?
1221 {
1222 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1223 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1224 },
1225 "unverifiable" => {
1226 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1227 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1228 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1229 }
1230 }
1231 _ => Ok(Self::Unknown { tag, body: value }),
1232 }
1233 }
1234}
1235
1236impl Serialize for RunningImageAgreement {
1237 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1238 where
1239 S: Serializer,
1240 {
1241 match self {
1242 Self::Match { evidence } => RunningImageAgreementWire::Match {
1243 evidence: evidence.clone(),
1244 }
1245 .serialize(serializer),
1246 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1247 running: running.clone(),
1248 disk: disk.clone(),
1249 }
1250 .serialize(serializer),
1251 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1252 reason: reason.clone(),
1253 }
1254 .serialize(serializer),
1255 Self::Unknown { body, .. } => body.serialize(serializer),
1256 }
1257 }
1258}
1259
1260impl Serialize for ReloadPathAgreement {
1261 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1262 where
1263 S: Serializer,
1264 {
1265 match self {
1266 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1267 Self::Mismatch {
1268 configured,
1269 spawned_from,
1270 } => ReloadPathAgreementWire::Mismatch {
1271 configured: configured.clone(),
1272 spawned_from: spawned_from.clone(),
1273 }
1274 .serialize(serializer),
1275 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1276 reason: reason.clone(),
1277 }
1278 .serialize(serializer),
1279 Self::Unknown { body, .. } => body.serialize(serializer),
1280 }
1281 }
1282}
1283
1284impl<'de> Deserialize<'de> for ReloadPathAgreement {
1285 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1286 where
1287 D: Deserializer<'de>,
1288 {
1289 let (tag, body) = read_tagged(deserializer, "status")?;
1290 match tag.as_str() {
1291 "match" => Ok(Self::Match),
1292 "mismatch" => {
1293 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1294 ReloadPathAgreementWire::Mismatch {
1295 configured,
1296 spawned_from,
1297 } => Ok(Self::Mismatch {
1298 configured,
1299 spawned_from,
1300 }),
1301 _ => unreachable!(),
1302 }
1303 }
1304 "unavailable" => match serde_json::from_value(body.into_value())
1305 .map_err(D::Error::custom)?
1306 {
1307 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1308 _ => unreachable!(),
1309 },
1310 _ => Ok(Self::Unknown { tag, body }),
1311 }
1312 }
1313}
1314
1315impl<'de> Deserialize<'de> for RunningImageAgreement {
1316 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1317 where
1318 D: serde::Deserializer<'de>,
1319 {
1320 let (tag, value) = read_tagged(deserializer, "status")?;
1321 match tag.as_str() {
1322 "match" => Ok(Self::Match {
1323 evidence: decode_running_image_evidence(
1324 ordered_field(&value, "evidence")
1325 .cloned()
1326 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1327 )
1328 .map_err(D::Error::custom)?,
1329 }),
1330 "mismatch" => Ok(Self::Mismatch {
1331 running: decode_running_image_evidence(
1332 ordered_field(&value, "running")
1333 .cloned()
1334 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1335 )
1336 .map_err(D::Error::custom)?,
1337 disk: decode_running_image_evidence(
1338 ordered_field(&value, "disk")
1339 .cloned()
1340 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1341 )
1342 .map_err(D::Error::custom)?,
1343 }),
1344 "unavailable" => Ok(Self::Unavailable {
1345 reason: serde_json::from_value(
1346 ordered_field(&value, "reason")
1347 .cloned()
1348 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1349 .into_value(),
1350 )
1351 .map_err(D::Error::custom)?,
1352 }),
1353 _ => Ok(Self::Unknown { tag, body: value }),
1354 }
1355 }
1356}
1357
1358impl Serialize for ChildResourceUsage {
1359 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1360 where
1361 S: Serializer,
1362 {
1363 match self {
1364 Self::Measured(reading) => {
1365 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1366 }
1367 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1368 reason: reason.clone(),
1369 }
1370 .serialize(serializer),
1371 Self::Unknown { body, .. } => body.serialize(serializer),
1372 }
1373 }
1374}
1375
1376impl<'de> Deserialize<'de> for ChildResourceUsage {
1377 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1378 where
1379 D: Deserializer<'de>,
1380 {
1381 let (tag, body) = read_tagged(deserializer, "status")?;
1382 match tag.as_str() {
1383 "measured" | "unavailable" => {
1384 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1385 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1386 ChildResourceUsageWire::Unavailable { reason } => {
1387 Ok(Self::Unavailable { reason })
1388 }
1389 }
1390 }
1391 _ => Ok(Self::Unknown { tag, body }),
1392 }
1393 }
1394}
1395
1396impl Serialize for RunningImageEvidence {
1397 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1398 where
1399 S: Serializer,
1400 {
1401 match self {
1402 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1403 digest: digest.clone(),
1404 }
1405 .serialize(serializer),
1406 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1407 device: *device,
1408 inode: *inode,
1409 }
1410 .serialize(serializer),
1411 Self::Unknown { body, .. } => body.serialize(serializer),
1412 }
1413 }
1414}
1415
1416impl<'de> Deserialize<'de> for RunningImageEvidence {
1417 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1418 where
1419 D: serde::Deserializer<'de>,
1420 {
1421 let (tag, value) = read_tagged(deserializer, "method")?;
1422 match tag.as_str() {
1423 "linux_proc_sha256" => {
1424 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1425 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1426 Ok(Self::LinuxProcSha256 { digest })
1427 }
1428 _ => unreachable!(),
1429 }
1430 }
1431 "macos_spawn_inode" => {
1432 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1433 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1434 Ok(Self::MacosSpawnInode { device, inode })
1435 }
1436 _ => unreachable!(),
1437 }
1438 }
1439 _ => Ok(Self::Unknown { tag, body: value }),
1440 }
1441 }
1442}
1443
1444impl Serialize for SupervisorRouteConsumer {
1445 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1446 where
1447 S: Serializer,
1448 {
1449 match self {
1450 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1451 module_id: module_id.clone(),
1452 }
1453 .serialize(serializer),
1454 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1455 connection_id: *connection_id,
1456 }
1457 .serialize(serializer),
1458 Self::Unknown { body, .. } => body.serialize(serializer),
1459 }
1460 }
1461}
1462
1463impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1464 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1465 where
1466 D: serde::Deserializer<'de>,
1467 {
1468 let (tag, value) = read_tagged(deserializer, "kind")?;
1469 match tag.as_str() {
1470 "reserved" => {
1471 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1472 SupervisorRouteConsumerWire::Reserved { module_id } => {
1473 Ok(Self::Reserved { module_id })
1474 }
1475 _ => unreachable!(),
1476 }
1477 }
1478 "direct" => {
1479 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1480 SupervisorRouteConsumerWire::Direct { connection_id } => {
1481 Ok(Self::Direct { connection_id })
1482 }
1483 _ => unreachable!(),
1484 }
1485 }
1486 _ => Ok(Self::Unknown { tag, body: value }),
1487 }
1488 }
1489}
1490
1491impl Serialize for StderrCaptureState {
1492 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1493 where
1494 S: Serializer,
1495 {
1496 match self {
1497 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1498 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1499 reason: reason.clone(),
1500 }
1501 .serialize(serializer),
1502 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1503 reason: reason.clone(),
1504 }
1505 .serialize(serializer),
1506 Self::Unknown { body, .. } => body.serialize(serializer),
1507 }
1508 }
1509}
1510
1511impl<'de> Deserialize<'de> for StderrCaptureState {
1512 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1513 where
1514 D: serde::Deserializer<'de>,
1515 {
1516 let (tag, value) = read_tagged(deserializer, "state")?;
1517 match tag.as_str() {
1518 "captured" => {
1519 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1520 StderrCaptureStateWire::Captured => Ok(Self::Captured),
1521 _ => unreachable!(),
1522 }
1523 }
1524 "incomplete" => match serde_json::from_value(value.into_value())
1525 .map_err(D::Error::custom)?
1526 {
1527 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1528 _ => unreachable!(),
1529 },
1530 "not_captured" => match serde_json::from_value(value.into_value())
1531 .map_err(D::Error::custom)?
1532 {
1533 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1534 _ => unreachable!(),
1535 },
1536 _ => Ok(Self::Unknown { tag, body: value }),
1537 }
1538 }
1539}
1540
1541impl Serialize for StderrTailEntry {
1542 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1543 where
1544 S: Serializer,
1545 {
1546 match self {
1547 Self::Line {
1548 text,
1549 truncated,
1550 at_ms,
1551 } => StderrTailEntryWire::Line {
1552 text: text.clone(),
1553 truncated: *truncated,
1554 at_ms: *at_ms,
1555 }
1556 .serialize(serializer),
1557 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1558 Self::Unknown { body, .. } => body.serialize(serializer),
1559 }
1560 }
1561}
1562
1563impl<'de> Deserialize<'de> for StderrTailEntry {
1564 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1565 where
1566 D: serde::Deserializer<'de>,
1567 {
1568 let (tag, value) = read_tagged(deserializer, "kind")?;
1569 match tag.as_str() {
1570 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1571 StderrTailEntryWire::Line {
1572 text,
1573 truncated,
1574 at_ms,
1575 } => Ok(Self::Line {
1576 text,
1577 truncated,
1578 at_ms,
1579 }),
1580 _ => unreachable!(),
1581 },
1582 "process_start" => {
1583 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1584 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1585 _ => unreachable!(),
1586 }
1587 }
1588 _ => Ok(Self::Unknown { tag, body: value }),
1589 }
1590 }
1591}
1592
1593fn is_zero_u64(value: &u64) -> bool {
1594 *value == 0
1595}
1596
1597fn default_true() -> bool {
1598 true
1599}
1600
1601#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1603pub struct TerminalHistory {
1604 pub daemon_started_at_ms: u64,
1606 pub entries: Vec<TerminalEntry>,
1607 #[serde(default, skip_serializing_if = "is_zero_u64")]
1610 pub dropped: u64,
1611 #[serde(default, skip_serializing_if = "is_zero_u64")]
1614 pub journal_skipped_lines: u64,
1615 #[serde(default, skip_serializing_if = "is_zero_u64")]
1617 pub journal_read_errors: u64,
1618 #[serde(default, skip_serializing_if = "is_zero_u64")]
1620 pub journal_write_failures: u64,
1621}
1622
1623#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1625pub struct TerminalEntry {
1626 #[serde(default, skip_serializing_if = "Option::is_none")]
1629 pub daemon_incarnation: Option<String>,
1630 #[serde(default, skip_serializing_if = "Option::is_none")]
1631 pub exit_code: Option<i32>,
1632 #[serde(default, skip_serializing_if = "Option::is_none")]
1633 pub exit_signal: Option<i32>,
1634 pub at_ms: u64,
1635 pub disposition: TerminalDisposition,
1636 #[serde(default, skip_serializing_if = "Option::is_none")]
1640 pub exit_kind: Option<TerminalExitKind>,
1641 #[serde(default, skip_serializing_if = "Option::is_none")]
1648 pub disposition_detail: Option<String>,
1649}
1650
1651#[derive(Debug, Clone, PartialEq, Eq)]
1656pub enum TerminalExitKind {
1657 Clean,
1658 Crash,
1659 DeliberateSeverance,
1660 Unknown(String),
1661}
1662
1663impl TerminalExitKind {
1664 fn wire_name(&self) -> &str {
1665 match self {
1666 Self::Clean => "clean",
1667 Self::Crash => "crash",
1668 Self::DeliberateSeverance => "deliberate_severance",
1669 Self::Unknown(value) => value,
1670 }
1671 }
1672}
1673
1674impl Serialize for TerminalExitKind {
1675 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1676 where
1677 S: serde::Serializer,
1678 {
1679 serializer.serialize_str(self.wire_name())
1680 }
1681}
1682
1683impl<'de> Deserialize<'de> for TerminalExitKind {
1684 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1685 where
1686 D: serde::Deserializer<'de>,
1687 {
1688 let value = String::deserialize(deserializer)?;
1689 Ok(match value.as_str() {
1690 "clean" => Self::Clean,
1691 "crash" => Self::Crash,
1692 "deliberate_severance" => Self::DeliberateSeverance,
1693 _ => Self::Unknown(value),
1694 })
1695 }
1696}
1697
1698open_string_enum! {
1699 TerminalDisposition {
1701 Stopped => "stopped",
1702 Disabled => "disabled",
1703 Failed => "failed",
1704 Restarting => "restarting",
1705 DaemonShutdown => "daemon_shutdown",
1710 }
1711}
1712
1713#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1714#[serde(rename_all = "snake_case")]
1715pub enum PollKind {
1716 Status,
1717 Liveness,
1718}
1719
1720#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1721pub struct CatalogEntry {
1722 pub module_id: String,
1723 #[serde(default = "default_true")]
1734 pub ready: bool,
1735 #[serde(default, skip_serializing_if = "Option::is_none")]
1739 pub not_ready: Option<NotReadyReason>,
1740 #[serde(default, skip_serializing_if = "Option::is_none")]
1761 pub module_version: Option<String>,
1762 pub roles: Vec<ProviderRole>,
1763 pub control_ops: Vec<String>,
1764 #[serde(default, skip_serializing_if = "Option::is_none")]
1769 pub capabilities: Option<CapabilityDeclarations>,
1770 #[serde(default, skip_serializing_if = "Option::is_none")]
1773 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
1774}
1775
1776#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1778pub struct NotReadyReason {
1779 pub reason: String,
1784 #[serde(default, skip_serializing_if = "Option::is_none")]
1787 pub capability: Option<String>,
1788}
1789
1790impl NotReadyReason {
1791 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
1792 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
1793}
1794
1795#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1796pub struct CapabilityRequirementStatus {
1797 pub consumer: String,
1798 pub capability: String,
1799 pub need: String,
1800 pub verdict: String,
1801 pub episode_seq: u64,
1802 pub config_satisfiable: bool,
1803 pub runtime_available: bool,
1804 pub detail: String,
1805}
1806
1807#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1808pub struct SupervisorRescanResult {
1809 pub added: Vec<String>,
1810 pub removed: Vec<String>,
1811 pub changed_pending_reload: Vec<String>,
1812 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1825 pub enabled_changes: Vec<String>,
1826 pub unchanged: u32,
1827 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1835 pub preview: bool,
1836 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1854 pub restart_required: Vec<String>,
1855 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1859 pub capability_warnings: Vec<String>,
1860}
1861
1862#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1878#[serde(rename_all = "snake_case")]
1879pub enum ModuleProtocol {
1880 #[default]
1884 Subc,
1885 None,
1894}
1895
1896#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1897pub struct SupervisorEntry {
1898 pub module_id: String,
1899 pub state: String,
1900 pub enabled: bool,
1901 pub live: bool,
1911 #[serde(default)]
1915 pub protocol: ModuleProtocol,
1916 pub health: SupervisorHealthStatus,
1917 #[serde(default, skip_serializing_if = "Option::is_none")]
1920 pub pending_reload: Option<PendingReloadVerdict>,
1921 #[serde(default)]
1927 pub last_probe_ms: Option<u64>,
1928 #[serde(default, skip_serializing_if = "Option::is_none")]
1932 pub last_exit_code: Option<i32>,
1933 #[serde(default, skip_serializing_if = "Option::is_none")]
1937 pub last_exit_signal: Option<i32>,
1938 #[serde(default, skip_serializing_if = "Option::is_none")]
1942 pub last_exit_ms: Option<u64>,
1943 #[serde(default, skip_serializing_if = "Option::is_none")]
1946 pub last_exit_kind: Option<TerminalExitKind>,
1947 #[serde(default, skip_serializing_if = "Option::is_none")]
1964 pub restart_count: Option<u32>,
1965 #[serde(default, skip_serializing_if = "Option::is_none")]
1968 pub max_restarts: Option<u32>,
1969 #[serde(default, skip_serializing_if = "Option::is_none")]
1972 pub lifetime_restarts: Option<u32>,
1973 #[serde(default, skip_serializing_if = "Option::is_none")]
1977 pub spawn_generation: Option<u64>,
1978 #[serde(default, skip_serializing_if = "Option::is_none")]
1988 pub restart_window_secs: Option<u64>,
1989 #[serde(default, skip_serializing_if = "Option::is_none")]
1993 pub drain_timeout_ms: Option<u64>,
1994 #[serde(default, skip_serializing_if = "Option::is_none")]
1997 pub restart_backoff_ms: Option<u64>,
1998 #[serde(default, skip_serializing_if = "Option::is_none")]
2001 pub restart_max_backoff_ms: Option<u64>,
2002 #[serde(default, skip_serializing_if = "Option::is_none")]
2015 pub resources: Option<ChildResourceUsage>,
2016}
2017
2018#[derive(Debug, Clone, PartialEq)]
2021pub enum ChildResourceUsage {
2022 Measured(ChildResourceReading),
2023 Unavailable {
2024 reason: ChildResourceUnavailableReason,
2025 },
2026 Unknown {
2029 tag: String,
2030 body: OrderedJsonObject,
2031 },
2032}
2033
2034#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2036pub struct ChildResourceReading {
2037 pub memory_bytes: u64,
2040 pub memory_kind: ChildMemoryKind,
2041 #[serde(default, skip_serializing_if = "Option::is_none")]
2044 pub swap_bytes: Option<u64>,
2045 pub cpu_user_ms: u64,
2049 pub cpu_system_ms: u64,
2052}
2053
2054open_string_enum! {
2055 ChildMemoryKind {
2057 PhysFootprint => "phys_footprint",
2061 ResidentSet => "resident_set",
2064 }
2065}
2066
2067open_string_enum! {
2068 ChildResourceUnavailableReason {
2070 NotRunning => "not_running",
2072 UnsupportedPlatform => "unsupported_platform",
2074 Unreadable => "unreadable",
2077 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2080 }
2081}
2082
2083#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2084#[serde(rename_all = "snake_case")]
2085pub enum SupervisorHealthStatus {
2086 Ok,
2087 Degraded,
2088 Failing,
2089 Unresponsive,
2090 Unknown,
2091}
2092
2093#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2094pub struct SupervisorHealthEntry {
2095 pub module_id: String,
2096 pub status: SupervisorHealthStatus,
2097 #[serde(default, skip_serializing_if = "Option::is_none")]
2103 pub detail: Option<String>,
2104 #[serde(default, skip_serializing_if = "Option::is_none")]
2109 pub metrics: Option<serde_json::Value>,
2110 pub consecutive_failures: u32,
2111 #[serde(default)]
2114 pub late_answer_count: u64,
2115 #[serde(default, skip_serializing_if = "Option::is_none")]
2117 pub last_late_answer_latency_ms: Option<u64>,
2118 #[serde(default)]
2123 pub last_action: Option<String>,
2124 #[serde(default)]
2127 pub last_action_ms: Option<u64>,
2128 #[serde(default, skip_serializing_if = "Option::is_none")]
2141 pub last_probe_ms: Option<u64>,
2142}
2143
2144#[cfg(test)]
2145mod tests {
2146 use super::*;
2147 use subc_protocol::{BindIdentity, RouteTarget};
2148
2149 #[test]
2150 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2151 let entry = TerminalEntry {
2152 daemon_incarnation: Some("daemon-before-restart".into()),
2153 exit_code: Some(1),
2154 exit_signal: None,
2155 at_ms: 1_700_000_000_123,
2156 disposition: TerminalDisposition::Restarting,
2157 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2158 disposition_detail: None,
2159 };
2160 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2161 assert_eq!(
2162 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2163 ["exit_kind"],
2164 "deliberate_severance"
2165 );
2166
2167 #[derive(serde::Deserialize)]
2168 struct LegacyTerminalEntry {
2169 exit_code: Option<i32>,
2170 exit_signal: Option<i32>,
2171 at_ms: u64,
2172 disposition: TerminalDisposition,
2173 }
2174
2175 let decoded: LegacyTerminalEntry =
2176 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2177 assert_eq!(decoded.exit_code, Some(1));
2178 assert_eq!(decoded.exit_signal, None);
2179 assert_eq!(decoded.at_ms, 1_700_000_000_123);
2180 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
2181
2182 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
2183 let future: TerminalEntry =
2184 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
2185 assert_eq!(
2186 future.exit_kind,
2187 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
2188 );
2189 }
2190
2191 #[test]
2192 fn terminal_incarnation_is_optional_for_older_daemons() {
2193 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
2194 "at_ms": 123,
2195 "disposition": "stopped"
2196 }))
2197 .unwrap();
2198 let encoded = serde_json::to_value(&entry).unwrap();
2199 assert_eq!(
2200 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
2201 (None, None)
2202 );
2203 }
2204
2205 #[test]
2206 fn route_poll_uses_kind_field() {
2207 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
2208 route_channel: 7,
2209 route_epoch: 11,
2210 kind: PollKind::Status,
2211 })
2212 .unwrap();
2213
2214 assert_eq!(body["op"], "route.poll");
2215 assert_eq!(body["route_epoch"], 11);
2216 assert_eq!(body["kind"], "status");
2217 assert!(body.get("op").is_some());
2218 }
2219
2220 #[test]
2221 fn route_open_is_internally_tagged() {
2222 let request = ClientControlRequest::RouteOpen {
2223 target: RouteTarget::ToolProvider {
2224 module_id: "aft".to_string(),
2225 },
2226 identity: BindIdentity::new("/tmp/project", "opencode", "session-1"),
2227 consumer_identity: None,
2228 consumer_capabilities: None,
2229 admission_facts: None,
2230 scope: None,
2231 };
2232
2233 let body = serde_json::to_value(request).unwrap();
2234 assert_eq!(body["op"], "route.open");
2235 assert_eq!(body["target"]["kind"], "tool_provider");
2236 assert!(body.get("consumer_identity").is_none());
2237 assert!(body.get("consumer_capabilities").is_none());
2238 }
2239
2240 #[test]
2241 fn route_open_without_optional_fields_still_decodes() {
2242 let body = serde_json::json!({
2243 "op": "route.open",
2244 "target": { "kind": "tool_provider", "module_id": "aft" },
2245 "identity": {
2246 "project_root": "/tmp/project",
2247 "harness": "opencode",
2248 "session": "session-1"
2249 }
2250 });
2251
2252 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
2253 let ClientControlRequest::RouteOpen {
2254 consumer_identity,
2255 consumer_capabilities,
2256 admission_facts,
2257 ..
2258 } = decoded
2259 else {
2260 panic!("decoded wrong request variant");
2261 };
2262 assert_eq!(consumer_identity, None);
2263 assert_eq!(consumer_capabilities, None);
2264 assert_eq!(admission_facts, None);
2265 }
2266
2267 #[test]
2268 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
2269 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
2270 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
2271 match decoded {
2272 ClientControlPush::RouteClosed {
2273 excluded_subscriptions,
2274 terminal,
2275 ..
2276 } => {
2277 assert_eq!(excluded_subscriptions, 0);
2278 assert_eq!(terminal, None);
2279 }
2280 other => panic!("unexpected push: {other:?}"),
2281 }
2282 assert!(!serde_json::to_string(&decoded)
2283 .unwrap()
2284 .contains("terminal"));
2285 }
2286
2287 #[test]
2288 fn old_route_closed_decoder_ignores_new_terminal_field() {
2289 #[derive(serde::Deserialize)]
2290 #[serde(tag = "op")]
2291 enum LegacyClientControlPush {
2292 #[serde(rename = "route.closed")]
2293 RouteClosed {
2294 module_id: String,
2295 reason: RouteCloseReason,
2296 drained: bool,
2297 abandoned: u32,
2298 },
2299 }
2300
2301 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
2302 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
2303 match decoded {
2304 LegacyClientControlPush::RouteClosed {
2305 module_id,
2306 reason,
2307 drained,
2308 abandoned,
2309 } => {
2310 assert_eq!(module_id, "aft-tools");
2311 assert_eq!(reason, RouteCloseReason::Crash);
2312 assert!(!drained);
2313 assert_eq!(abandoned, 0);
2314 }
2315 }
2316 }
2317
2318 #[test]
2319 fn supervisor_routes_is_a_control_plane_request() {
2320 let body = serde_json::json!({
2321 "op": "supervisor.routes",
2322 "module_id": "aft"
2323 });
2324
2325 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
2326 assert_eq!(serde_json::to_value(request).unwrap(), body);
2327 }
2328
2329 #[test]
2330 fn diagnostic_string_enums_retain_unknown_wire_values() {
2331 let reason: RunningImageUnavailableReason =
2332 serde_json::from_str("\"future_reason\"").unwrap();
2333 let disposition: TerminalDisposition =
2334 serde_json::from_str("\"future_disposition\"").unwrap();
2335
2336 assert_eq!(
2337 reason,
2338 RunningImageUnavailableReason::Unknown("future_reason".to_string())
2339 );
2340 assert_eq!(
2341 disposition,
2342 TerminalDisposition::Unknown("future_disposition".to_string())
2343 );
2344 }
2345
2346 #[test]
2347 fn diagnostic_string_enums_preserve_existing_wire_names() {
2348 let names = [
2349 (RunningImageUnavailableReason::NotRunning, "not_running"),
2350 (
2351 RunningImageUnavailableReason::UnsupportedPlatform,
2352 "unsupported_platform",
2353 ),
2354 (
2355 RunningImageUnavailableReason::RunningExecutableUnreadable,
2356 "running_executable_unreadable",
2357 ),
2358 (
2359 RunningImageUnavailableReason::SpawnedPathUnreadable,
2360 "spawned_path_unreadable",
2361 ),
2362 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
2363 (
2364 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
2365 "process_identity_unconfirmed",
2366 ),
2367 ];
2368 for (value, expected) in names {
2369 let wire = serde_json::to_string(&value).unwrap();
2370 assert_eq!(wire, format!("\"{expected}\""));
2371 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
2372 assert_eq!(decoded, value);
2373 }
2374
2375 for (value, expected) in [
2376 (TerminalDisposition::Stopped, "stopped"),
2377 (TerminalDisposition::Disabled, "disabled"),
2378 (TerminalDisposition::Failed, "failed"),
2379 (TerminalDisposition::Restarting, "restarting"),
2380 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
2381 ] {
2382 let wire = serde_json::to_string(&value).unwrap();
2383 assert_eq!(wire, format!("\"{expected}\""));
2384 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
2385 assert_eq!(decoded, value);
2386 }
2387 }
2388
2389 #[test]
2390 fn diagnostic_string_enums_reject_non_string_bodies() {
2391 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
2392 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
2393 }
2394
2395 #[test]
2396 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
2397 let body = serde_json::json!({
2398 "op": "supervisor.provenance",
2399 "daemon": {
2400 "daemon_build": {},
2401 "daemon_observed": {
2402 "running_image": {
2403 "status": "unavailable",
2404 "reason": "not_running"
2405 }
2406 }
2407 },
2408 "modules": [
2409 {
2410 "module_id": "future",
2411 "module_declared": { "status": "unverifiable" },
2412 "daemon_observed": {
2413 "running_image": {
2414 "status": "unavailable",
2415 "reason": "future_reason"
2416 }
2417 }
2418 },
2419 {
2420 "module_id": "healthy-a",
2421 "module_declared": { "status": "unverifiable" },
2422 "daemon_observed": {
2423 "running_image": {
2424 "status": "match",
2425 "evidence": {
2426 "method": "linux_proc_sha256",
2427 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
2428 }
2429 }
2430 }
2431 },
2432 {
2433 "module_id": "healthy-b",
2434 "module_declared": { "status": "unverifiable" },
2435 "daemon_observed": {
2436 "running_image": {
2437 "status": "unavailable",
2438 "reason": "unsupported_platform"
2439 }
2440 }
2441 }
2442 ]
2443 });
2444
2445 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
2446 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
2447 panic!("decoded wrong response variant");
2448 };
2449 assert_eq!(modules.len(), 3);
2450 assert_eq!(modules[0].module_id, "future");
2451 assert_eq!(
2452 modules[0].daemon_observed.running_image,
2453 RunningImageAgreement::Unavailable {
2454 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
2455 }
2456 );
2457 assert_eq!(modules[1].module_id, "healthy-a");
2458 assert_eq!(modules[2].module_id, "healthy-b");
2459 }
2460
2461 #[test]
2462 fn tagged_unknown_values_retain_tag_and_body() {
2463 macro_rules! assert_unknown_round_trip {
2464 ($ty:ident, $field:literal, $value:expr) => {
2465 let value = $value;
2466 let wire = serde_json::to_string(&value).unwrap();
2467 let decoded: $ty = serde_json::from_str(&wire).unwrap();
2468 match decoded {
2469 $ty::Unknown { tag, body } => {
2470 assert_eq!(tag, value[$field].as_str().unwrap());
2471 assert_eq!(serde_json::to_value(&body).unwrap(), value);
2472 }
2473 _ => panic!("decoded known variant"),
2474 }
2475 };
2476 }
2477
2478 assert_unknown_round_trip!(
2479 ModuleDeclaredProvenance,
2480 "status",
2481 serde_json::json!({"status": "future", "build": {"version": 7}})
2482 );
2483 assert_unknown_round_trip!(
2484 RunningImageAgreement,
2485 "status",
2486 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
2487 );
2488 assert_unknown_round_trip!(
2489 RunningImageEvidence,
2490 "method",
2491 serde_json::json!({"method": "future", "digest": "abc"})
2492 );
2493 assert_unknown_round_trip!(
2494 SupervisorRouteConsumer,
2495 "kind",
2496 serde_json::json!({"kind": "future", "module_id": "m"})
2497 );
2498 assert_unknown_round_trip!(
2499 StderrCaptureState,
2500 "state",
2501 serde_json::json!({"state": "future", "reason": "because"})
2502 );
2503 assert_unknown_round_trip!(
2504 StderrTailEntry,
2505 "kind",
2506 serde_json::json!({"kind": "future", "text": "line"})
2507 );
2508 assert_unknown_round_trip!(
2509 ChildResourceUsage,
2510 "status",
2511 serde_json::json!({"status": "future", "memory_bytes": 1})
2512 );
2513 }
2514
2515 #[test]
2516 fn child_resource_usage_round_trips_both_known_states() {
2517 let measured = ChildResourceUsage::Measured(ChildResourceReading {
2518 memory_bytes: 0,
2519 memory_kind: ChildMemoryKind::ResidentSet,
2520 swap_bytes: Some(0),
2521 cpu_user_ms: 0,
2522 cpu_system_ms: 0,
2523 });
2524 let wire = serde_json::to_value(&measured).unwrap();
2525 assert_eq!(
2526 wire,
2527 serde_json::json!({
2528 "status": "measured",
2529 "memory_bytes": 0,
2530 "memory_kind": "resident_set",
2531 "swap_bytes": 0,
2532 "cpu_user_ms": 0,
2533 "cpu_system_ms": 0
2534 })
2535 );
2536 assert_eq!(
2537 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
2538 measured
2539 );
2540
2541 let unavailable = ChildResourceUsage::Unavailable {
2542 reason: ChildResourceUnavailableReason::NotRunning,
2543 };
2544 let wire = serde_json::to_value(&unavailable).unwrap();
2545 assert_eq!(
2546 wire,
2547 serde_json::json!({"status": "unavailable", "reason": "not_running"})
2548 );
2549 assert_eq!(
2550 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
2551 unavailable
2552 );
2553 }
2554
2555 #[test]
2556 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
2557 let stamped: StderrTailEntry = serde_json::from_str(
2561 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
2562 )
2563 .unwrap();
2564 assert_eq!(
2565 stamped,
2566 StderrTailEntry::Line {
2567 text: "boom".to_string(),
2568 truncated: true,
2569 at_ms: Some(1_789_801_440_685),
2570 }
2571 );
2572 let unstamped: StderrTailEntry =
2573 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
2574 assert_eq!(
2575 unstamped,
2576 StderrTailEntry::Line {
2577 text: "boom".to_string(),
2578 truncated: false,
2579 at_ms: None,
2580 }
2581 );
2582 assert_eq!(
2585 serde_json::to_string(&unstamped).unwrap(),
2586 r#"{"kind":"line","text":"boom"}"#
2587 );
2588 assert_eq!(
2589 serde_json::to_value(&stamped).unwrap()["at_ms"],
2590 serde_json::json!(1_789_801_440_685u64)
2591 );
2592 }
2593
2594 #[test]
2595 fn tagged_unknown_values_round_trip_the_original_json() {
2596 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
2597 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
2598 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
2599 }
2600
2601 #[test]
2602 fn tagged_unknown_values_round_trip_trailing_tag() {
2603 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
2604 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
2605 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
2606
2607 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
2608 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
2609 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
2610 }
2611
2612 #[test]
2613 fn tagged_unknown_values_round_trip_middle_tag() {
2614 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
2615 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
2616 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
2617
2618 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
2619 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
2620 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
2621 }
2622
2623 #[test]
2624 fn tagged_unknown_values_round_trip_deep_payload() {
2625 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
2626 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
2627 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
2628
2629 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
2630 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
2631 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
2632 }
2633
2634 #[test]
2635 fn tagged_unknown_values_reject_non_object_bodies() {
2636 for wire in ["42", r#""future""#, "[]"] {
2637 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
2638 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
2639 }
2640 }
2641
2642 #[test]
2643 fn duplicate_discriminators_reject_without_panicking() {
2644 assert_eq!(
2645 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
2646 .unwrap(),
2647 ModuleDeclaredProvenance::Unverifiable
2648 );
2649 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
2650 .unwrap()
2651 {
2652 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
2653 _ => panic!("future discriminator decoded as a known variant"),
2654 }
2655
2656 let wires = [
2657 r#"{"status":"reported","status":"unverifiable"}"#,
2658 r#"{"status":"unverifiable","status":"reported"}"#,
2659 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
2660 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
2661 ];
2662
2663 for wire in wires {
2664 let result =
2665 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
2666 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
2667 assert!(
2668 result.unwrap().is_err(),
2669 "duplicate discriminator decoded: {wire}"
2670 );
2671 }
2672
2673 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
2674 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
2675 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
2676 assert!(
2677 result.unwrap().is_err(),
2678 "duplicate discriminator decoded: {wire}"
2679 );
2680 }
2681
2682 #[test]
2683 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
2684 let known_wire =
2685 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
2686 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
2687 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
2688
2689 for wire in [
2690 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
2691 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
2692 ] {
2693 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
2694 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
2695 }
2696
2697 for wire in [
2698 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
2699 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
2700 ] {
2701 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
2702 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
2703 }
2704
2705 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
2706 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
2707 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
2708
2709 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
2710 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
2711 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
2712 }
2713
2714 #[test]
2715 fn tagged_unknown_member_does_not_discard_known_siblings() {
2716 let body = serde_json::json!({
2717 "modules": [{
2718 "module_id": "target",
2719 "routes": [
2720 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
2721 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
2722 ]
2723 }]
2724 });
2725 let decoded: ClientControlResponse = serde_json::from_value(
2726 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
2727 )
2728 .unwrap();
2729 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
2730 panic!("decoded wrong response variant");
2731 };
2732 assert_eq!(modules[0].routes.len(), 2);
2733 assert_eq!(
2734 modules[0].routes[1].consumer,
2735 SupervisorRouteConsumer::Direct { connection_id: 7 }
2736 );
2737 }
2738}
2739
2740#[cfg(test)]
2741mod launch_nonce_redaction_tests {
2742 use super::*;
2743
2744 const NONCE: &str = "nonce-f00dfeed1234abcd";
2745
2746 fn identity() -> ConsumerIdentity {
2747 ConsumerIdentity {
2748 module_id: "wernicke".to_string(),
2749 launch_nonce: NONCE.to_string(),
2750 }
2751 }
2752
2753 #[test]
2754 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
2755 let printed = format!("{:?}", identity());
2756 assert!(printed.contains("wernicke"), "{printed}");
2757 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
2758 }
2759
2760 #[test]
2761 fn route_open_request_debug_never_prints_the_nonce() {
2762 let request = ClientControlRequest::RouteOpen {
2763 target: subc_protocol::RouteTarget::ToolProvider {
2764 module_id: "broca".to_string(),
2765 },
2766 identity: subc_protocol::BindIdentity::new(
2767 PathBuf::from("/tmp/project"),
2768 "test".to_string(),
2769 "session".to_string(),
2770 ),
2771 consumer_identity: Some(identity()),
2772 consumer_capabilities: None,
2773 admission_facts: None,
2774 scope: None,
2775 };
2776 let printed = format!("{request:?}");
2777 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
2778 }
2779}