1#![forbid(unsafe_code)]
9
10use std::{collections::BTreeMap, path::PathBuf};
11
12use serde::{
13 de::{Error as _, MapAccess, SeqAccess, Visitor},
14 ser::SerializeMap,
15 Deserialize, Deserializer, Serialize, Serializer,
16};
17use subc_protocol::{
18 manifest::{
19 CapabilityDeclarations, EventDeclaration, ManifestProvenance, OperationDelivery,
20 OperationPayload, ProviderRole, RichUiDescriptor, SelfSignalDeclaration,
21 },
22 scope::ScopeSelector,
23 session::HealthStatus,
24 BindIdentity, RouteTarget,
25};
26
27pub use subc_protocol::claim::{
28 Claim, ClaimMintReply, ClaimMintRequest, ClaimPresentReply, ClaimPresentRequest, ClaimPurpose,
29 ClaimRateLimitedDetail,
30};
31pub use subc_protocol::peer::CallerOrigin as CatalogOrigin;
32pub use subc_protocol::RouteCloseReason;
33use subc_protocol::{peer::MAX_ATTESTATION_INTEGER, provider_declarations::ProviderDeclarations};
34
35mod activity;
36pub use activity::*;
37
38mod scope_served_by;
39pub use scope_served_by::*;
40
41macro_rules! open_string_enum {
42 (
43 $(#[$meta:meta])*
44 $name:ident {
45 $( $(#[$variant_meta:meta])* $variant:ident => $wire_name:literal ),+ $(,)?
46 }
47 ) => {
48 $(#[$meta])*
49 #[derive(Debug, Clone, PartialEq, Eq)]
50 pub enum $name {
51 $( $(#[$variant_meta])* $variant, )+
52 Unknown(String),
53 }
54
55 impl $name {
56 fn wire_name(&self) -> &str {
57 match self {
58 $( Self::$variant => $wire_name, )+
59 Self::Unknown(value) => value,
60 }
61 }
62 }
63
64 impl Serialize for $name {
65 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
66 where
67 S: serde::Serializer,
68 {
69 serializer.serialize_str(self.wire_name())
70 }
71 }
72
73 impl<'de> Deserialize<'de> for $name {
74 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
75 where
76 D: serde::Deserializer<'de>,
77 {
78 let value = String::deserialize(deserializer)?;
79 Ok(match value.as_str() {
80 $( $wire_name => Self::$variant, )+
81 _ => Self::Unknown(value),
82 })
83 }
84 }
85 };
86}
87
88pub mod policy_root;
89mod rescan_checked;
90pub mod upgrade_in_place;
91pub use rescan_checked::*;
92
93mod app_open;
94pub use app_open::*;
95
96mod connection_describe;
97pub use connection_describe::*;
98
99mod scope_watch;
100pub use scope_watch::*;
101
102mod subtree;
103pub use subtree::*;
104mod tree;
105pub use tree::*;
106
107#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
109pub struct ConsumerIdentity {
110 pub module_id: String,
111 pub launch_nonce: String,
112}
113
114impl std::fmt::Debug for ConsumerIdentity {
119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120 f.debug_struct("ConsumerIdentity")
121 .field("module_id", &self.module_id)
122 .field(
123 "launch_nonce",
124 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
125 )
126 .finish()
127 }
128}
129
130pub mod config;
141
142pub mod ops {
143 pub const SERVER: &str = "server.";
144 pub const CATALOG: &str = "catalog.";
145 pub const ROUTE: &str = "route.";
146 pub const SUPERVISOR: &str = "supervisor.";
147 pub const CONFIG: &str = "config.";
148
149 pub const SERVER_DESCRIBE: &str = "server.describe";
150 pub const DAEMON_SHUTDOWN_INTENT: &str = "daemon.shutdown_intent";
151 pub const DAEMON_UPGRADE_IN_PLACE: &str = "daemon.upgrade_in_place";
152 pub const CATALOG_LIST: &str = "catalog.list";
153 pub const CATALOG_WATCH: &str = "catalog.watch";
154 pub const SCOPE_WATCH: &str = "scope.watch";
155 pub const ROUTE_OPEN: &str = "route.open";
156 pub const ROUTE_POLL: &str = "route.poll";
157 pub const ROUTE_CLOSING: &str = "route.closing";
158 pub const ROUTE_CLOSED: &str = "route.closed";
159 pub const SUPERVISOR_LIST: &str = "supervisor.list";
160 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
161 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
162 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
163 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
164 pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
165 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
166 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
167 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
168 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
169 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
170 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
171 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
172 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
173 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
174 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
175 pub const ACTIVITY_RECORD: &str = "activity.record";
176 pub const ACTIVITY_QUERY: &str = "activity.query";
177 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
178 pub const APP_OPEN: &str = "app.open";
179 pub const CONNECTION_DESCRIBE: &str = "connection.describe";
180}
181
182#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
184#[serde(tag = "op")]
185#[allow(clippy::large_enum_variant)]
188pub enum ClientControlRequest {
189 #[serde(rename = "policy_root.get")]
190 PolicyRoot(subc_protocol::policy_root::GetPolicyRoot),
191 #[serde(rename = "policy_root.set")]
192 PolicyRootSet(policy_root::SetPolicyRoot),
193 #[serde(rename = "policy_root.recover")]
194 PolicyRootRecover(policy_root::RecoverPolicyRoot),
195 #[serde(rename = "daemon.shutdown_intent")]
198 DaemonShutdownIntent {
199 #[serde(default)]
200 intent: serde_json::Value,
201 },
202 #[serde(rename = "daemon.upgrade_in_place")]
203 DaemonUpgradeInPlace { executable_sha256: String },
204 #[serde(rename = "server.describe")]
205 ServerDescribe {},
206 #[serde(rename = "catalog.list")]
207 CatalogList {
208 #[serde(default)]
213 module_id: Option<String>,
214 },
215 #[serde(rename = "route.open")]
216 RouteOpen {
217 target: RouteTarget,
218 identity: BindIdentity,
219 #[serde(default, skip_serializing_if = "Option::is_none")]
228 consumer_identity: Option<ConsumerIdentity>,
229 #[serde(default, skip_serializing_if = "Option::is_none")]
237 consumer_capabilities: Option<Vec<String>>,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
249 role_versions: Option<BTreeMap<String, String>>,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
254 busy_refusals: Option<bool>,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
257 admission_facts: Option<serde_json::Value>,
258 #[serde(default, skip_serializing_if = "Option::is_none")]
265 scope: Option<ScopeSelector>,
266 },
267 #[serde(rename = "route.poll")]
268 RoutePoll {
269 route_channel: u16,
270 route_epoch: u32,
271 kind: PollKind,
272 },
273 #[serde(rename = "supervisor.list")]
274 SupervisorList {},
275 #[serde(rename = "supervisor.spawn_snapshot")]
277 SupervisorSpawnSnapshot {},
278 #[serde(rename = "supervisor.spawn_subscribe")]
294 SupervisorSpawnSubscribe {
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 since: Option<SpawnCursor>,
297 },
298 #[serde(rename = "supervisor.restart")]
299 SupervisorRestart {
300 module_id: String,
301 #[serde(default, skip_serializing_if = "Option::is_none")]
311 drain_timeout_ms: Option<u64>,
312 },
313 #[serde(rename = "supervisor.swap")]
328 SupervisorSwap {
329 module_id: String,
330 #[serde(default, skip_serializing_if = "Option::is_none")]
333 ready_timeout_ms: Option<u64>,
334 },
335 #[serde(rename = "supervisor.reload")]
336 SupervisorReload { module_id: String },
337 #[serde(rename = "supervisor.rescan")]
338 SupervisorRescan {
339 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
359 preview: bool,
360 },
361 #[serde(rename = "supervisor.rescan_checked")]
385 SupervisorRescanChecked {
386 preview: bool,
387 #[serde(default, skip_serializing_if = "Option::is_none")]
388 candidate: Option<String>,
389 #[serde(default, skip_serializing_if = "Option::is_none")]
390 expect: Option<RescanExpect>,
391 },
392 #[serde(rename = "supervisor.release_reserved")]
396 SupervisorReleaseReserved { module_id: String },
397 #[serde(rename = "supervisor.set_enabled")]
398 SupervisorSetEnabled { module_id: String, enabled: bool },
399 #[serde(rename = "supervisor.health_probe")]
400 SupervisorHealthProbe { module_id: String },
401 #[serde(rename = "supervisor.health")]
402 SupervisorHealth {},
403 #[serde(rename = "supervisor.routes")]
416 SupervisorRoutes {
417 #[serde(default, skip_serializing_if = "Option::is_none")]
418 module_id: Option<String>,
419 },
420 #[serde(rename = "supervisor.provenance")]
423 SupervisorProvenance {
424 #[serde(default, skip_serializing_if = "Option::is_none")]
425 module_id: Option<String>,
426 },
427 #[serde(rename = "supervisor.stderr_tail")]
435 SupervisorStderrTail {
436 module_id: String,
437 #[serde(default, skip_serializing_if = "Option::is_none")]
438 max_lines: Option<u32>,
439 #[serde(default, skip_serializing_if = "Option::is_none")]
440 max_bytes: Option<u32>,
441 },
442 #[serde(rename = "supervisor.terminals")]
455 SupervisorTerminals { module_id: String },
456}
457
458#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
460#[serde(tag = "op")]
461pub enum ClientControlResponse {
462 #[serde(rename = "policy_root.get")]
463 PolicyRoot(subc_protocol::policy_root::PolicyRoot),
464 #[serde(rename = "policy_root.set")]
465 PolicyRootSet(subc_protocol::policy_root::PolicyRootChange),
466 #[serde(rename = "policy_root.recover")]
467 PolicyRootRecover(subc_protocol::policy_root::PolicyRootChange),
468 #[serde(rename = "daemon.shutdown_intent")]
469 DaemonShutdownIntent { intent: String, expires_at_ms: u64 },
470 #[serde(rename = "server.describe")]
471 ServerDescribe {
472 protocol_ver: u8,
473 subc_ops: Vec<String>,
474 capabilities: Vec<String>,
475 connected_clients: u64,
476 #[serde(default, skip_serializing_if = "Option::is_none")]
477 counters: Option<serde_json::Value>,
478 #[serde(default, skip_serializing_if = "Option::is_none")]
485 build_git_sha: Option<String>,
486 #[serde(default, skip_serializing_if = "Option::is_none")]
492 build_lock_digest: Option<String>,
493 #[serde(default, skip_serializing_if = "Vec::is_empty")]
497 capability_requirements: Vec<CapabilityRequirementStatus>,
498 #[serde(default, skip_serializing_if = "Option::is_none")]
503 machine_id: Option<String>,
504 #[serde(default, skip_serializing_if = "Option::is_none")]
513 config_path: Option<PathBuf>,
514 },
515 #[serde(rename = "catalog.list")]
516 CatalogList {
517 generation: u64,
518 modules: Vec<CatalogEntry>,
519 subc_ops: Vec<String>,
520 },
521 #[serde(rename = "route.open")]
522 RouteOpen {
523 route_channel: u16,
524 route_epoch: u32,
525 #[serde(default, skip_serializing_if = "Option::is_none")]
527 request_window: Option<usize>,
528 #[serde(default, skip_serializing_if = "Option::is_none")]
530 watch_window: Option<usize>,
531 },
532 #[serde(rename = "route.poll")]
533 RoutePoll {
534 route_channel: u16,
535 route_epoch: u32,
536 status: Option<String>,
537 live: Option<bool>,
538 },
539 #[serde(rename = "supervisor.list")]
540 SupervisorList {
541 generation: u64,
542 modules: Vec<SupervisorEntry>,
543 #[serde(default, skip_serializing_if = "Option::is_none")]
544 daemon: Option<DaemonResources>,
545 #[serde(default, skip_serializing_if = "Option::is_none")]
546 agent_commands: Option<Vec<AgentCommandResources>>,
547 },
548 #[serde(rename = "supervisor.spawn_snapshot")]
549 SupervisorSpawnSnapshot {
550 #[serde(flatten)]
551 snapshot: SpawnSnapshot,
552 },
553 #[serde(rename = "supervisor.ack")]
554 SupervisorAck { module_id: String, applied: bool },
555 #[serde(rename = "supervisor.rescan")]
556 SupervisorRescan {
557 #[serde(flatten)]
558 result: SupervisorRescanResult,
559 },
560 #[serde(rename = "supervisor.health_probe")]
561 SupervisorHealthProbe {
562 module_id: String,
563 status: HealthStatus,
564 #[serde(default, skip_serializing_if = "Option::is_none")]
565 detail: Option<String>,
566 #[serde(default, skip_serializing_if = "Option::is_none")]
567 metrics: Option<serde_json::Value>,
568 },
569 #[serde(rename = "supervisor.health")]
570 SupervisorHealth {
571 generation: u64,
572 modules: Vec<SupervisorHealthEntry>,
573 },
574 #[serde(rename = "supervisor.routes")]
575 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
576 #[serde(rename = "supervisor.provenance")]
577 SupervisorProvenance {
578 daemon: SupervisorDaemonProvenance,
579 modules: Vec<SupervisorModuleProvenance>,
580 },
581 #[serde(rename = "supervisor.stderr_tail")]
582 SupervisorStderrTail {
583 module_id: String,
584 #[serde(flatten)]
585 tail: StderrTail,
586 },
587 #[serde(rename = "supervisor.terminals")]
588 SupervisorTerminals {
589 module_id: String,
590 #[serde(flatten)]
591 terminals: TerminalHistory,
592 },
593}
594
595pub const ROUTE_CLOSE_REASONS_CAPABILITY: &str = "route-close-reasons/v1";
597
598#[non_exhaustive]
602#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
603pub struct RouteOpenRequestExt {
604 #[serde(default, skip_serializing_if = "Option::is_none")]
605 pub accepts_close_reasons: Option<Vec<String>>,
606}
607
608impl RouteOpenRequestExt {
609 pub fn new() -> Self {
610 Self::default()
611 }
612
613 #[must_use]
614 pub fn with_accepts_close_reasons(mut self, reasons: Option<Vec<String>>) -> Self {
615 self.accepts_close_reasons = reasons;
616 self
617 }
618
619 pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
621 require_route_open_object(body)?;
622 serde_json::from_value(body.clone())
623 }
624
625 pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
628 write_route_open_ext(body, self, &["accepts_close_reasons"])
629 }
630}
631
632#[non_exhaustive]
635#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
636pub struct RouteOpenReplyExt {
637 #[serde(
639 default,
640 skip_serializing_if = "Option::is_none",
641 deserialize_with = "deserialize_route_open_target"
642 )]
643 pub target: Option<RouteOpenTarget>,
644}
645
646impl RouteOpenReplyExt {
647 pub fn new() -> Self {
648 Self::default()
649 }
650
651 #[must_use]
652 pub fn with_target(mut self, target: Option<RouteOpenTarget>) -> Self {
653 self.target = target;
654 self
655 }
656
657 pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
659 require_route_open_object(body)?;
660 serde_json::from_value(body.clone())
661 }
662
663 pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
666 write_route_open_ext(body, self, &["target"])
667 }
668}
669
670fn require_route_open_object(body: &serde_json::Value) -> serde_json::Result<()> {
671 if body.is_object()
672 && body.get("op").and_then(serde_json::Value::as_str) == Some(ops::ROUTE_OPEN)
673 {
674 Ok(())
675 } else {
676 Err(serde_json::Error::custom(
677 "expected a route.open body object",
678 ))
679 }
680}
681
682fn write_route_open_ext(
683 body: &mut serde_json::Value,
684 ext: &impl Serialize,
685 keys: &[&str],
686) -> serde_json::Result<()> {
687 require_route_open_object(body)?;
688 let serde_json::Value::Object(fields) = serde_json::to_value(ext)? else {
689 unreachable!("route.open companions serialize as objects");
690 };
691 let object = body.as_object_mut().expect("validated route.open object");
692 for key in keys {
693 object.remove(*key);
694 }
695 object.extend(fields);
696 Ok(())
697}
698
699#[non_exhaustive]
701#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
702#[serde(rename_all = "snake_case")]
703pub enum RouteOpenTargetKind {
704 Spawn,
705 Prefix,
706 Unsupervised,
707 #[serde(other)]
708 Unknown,
709}
710
711#[non_exhaustive]
714#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
715pub struct RouteOpenTarget {
716 pub incarnation: String,
717 pub kind: RouteOpenTargetKind,
718 #[serde(skip_serializing_if = "Option::is_none")]
719 pub spawn: Option<u64>,
720 #[serde(skip_serializing_if = "Option::is_none")]
721 pub authority_epoch: Option<u64>,
722 pub first_party: bool,
723 #[serde(skip_serializing_if = "Option::is_none")]
724 pub approved_declarations_digest: Option<String>,
725}
726
727impl RouteOpenTarget {
728 pub fn new(
731 incarnation: impl Into<String>,
732 kind: RouteOpenTargetKind,
733 spawn: Option<u64>,
734 authority_epoch: Option<u64>,
735 first_party: bool,
736 approved_declarations_digest: Option<String>,
737 ) -> serde_json::Result<Self> {
738 serde_json::from_value(serde_json::json!({
739 "incarnation": incarnation.into(), "kind": kind,
740 "spawn": spawn, "authority_epoch": authority_epoch,
741 "first_party": first_party,
742 "approved_declarations_digest": approved_declarations_digest,
743 }))
744 }
745}
746
747impl<'de> Deserialize<'de> for RouteOpenTarget {
748 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
749 decode_route_open_target(serde_json::Value::deserialize(decoder)?)
750 .map_err(D::Error::custom)?
751 .ok_or_else(|| D::Error::custom("incomplete route.open target"))
752 }
753}
754
755fn deserialize_route_open_target<'de, D: Deserializer<'de>>(
756 decoder: D,
757) -> Result<Option<RouteOpenTarget>, D::Error> {
758 decode_route_open_target(serde_json::Value::deserialize(decoder)?).map_err(D::Error::custom)
759}
760
761fn decode_route_open_target(
762 mut value: serde_json::Value,
763) -> serde_json::Result<Option<RouteOpenTarget>> {
764 if value.is_null() {
765 return Ok(None);
766 }
767 let object = value
768 .as_object_mut()
769 .ok_or_else(|| serde_json::Error::custom("expected target object"))?;
770 let is_spawn = object.get("kind").and_then(serde_json::Value::as_str) == Some("spawn");
771 if is_spawn {
772 for field in ["spawn", "authority_epoch"] {
774 if let Some(integer) = object.get(field) {
775 deserialize_optional_attestation_integer(integer)?;
776 }
777 }
778 } else {
779 for field in ["spawn", "authority_epoch", "approved_declarations_digest"] {
780 object.remove(field);
781 }
782 }
783 if ["incarnation", "kind", "first_party"]
784 .iter()
785 .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null))
786 || (is_spawn
787 && ["spawn", "authority_epoch", "approved_declarations_digest"]
788 .iter()
789 .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null)))
790 {
791 return Ok(None);
792 }
793 #[derive(Deserialize)]
794 struct Wire {
795 incarnation: String,
796 kind: RouteOpenTargetKind,
797 spawn: Option<u64>,
798 authority_epoch: Option<u64>,
799 first_party: bool,
800 approved_declarations_digest: Option<String>,
801 }
802 let wire: Wire = serde_json::from_value(value)?;
803 Ok(Some(RouteOpenTarget {
804 incarnation: wire.incarnation,
805 kind: wire.kind,
806 spawn: wire.spawn,
807 authority_epoch: wire.authority_epoch,
808 first_party: is_spawn && wire.first_party,
809 approved_declarations_digest: wire.approved_declarations_digest,
810 }))
811}
812
813fn deserialize_optional_attestation_integer<'de, D: Deserializer<'de>>(
814 decoder: D,
815) -> Result<Option<u64>, D::Error> {
816 let value = Option::<u64>::deserialize(decoder)?;
817 if value.is_some_and(|integer| integer > MAX_ATTESTATION_INTEGER) {
818 return Err(D::Error::custom("attestation integer exceeds 2^53-1"));
819 }
820 Ok(value)
821}
822
823#[non_exhaustive]
826#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
827#[serde(tag = "op", rename = "catalog.watch")]
828pub struct CatalogWatchRequest {}
829
830impl CatalogWatchRequest {
831 pub const OP: &'static str = ops::CATALOG_WATCH;
832
833 pub fn new() -> Self {
834 Self {}
835 }
836}
837
838#[non_exhaustive]
842#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
843#[serde(tag = "op", rename = "catalog.watch")]
844pub struct CatalogWatchResponse {
845 pub generation: u64,
846}
847
848impl CatalogWatchResponse {
849 pub const OP: &'static str = ops::CATALOG_WATCH;
850
851 pub fn new(generation: u64) -> Self {
852 Self { generation }
853 }
854}
855
856impl<'de> Deserialize<'de> for CatalogWatchRequest {
857 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
858 #[derive(Deserialize)]
859 #[serde(tag = "op")]
860 enum Wire {
861 #[serde(rename = "catalog.watch")]
862 Body {},
863 }
864 let Wire::Body {} = Wire::deserialize(decoder)?;
865 Ok(Self::new())
866 }
867}
868
869impl<'de> Deserialize<'de> for CatalogWatchResponse {
870 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
871 #[derive(Deserialize)]
872 #[serde(tag = "op")]
873 enum Wire {
874 #[serde(rename = "catalog.watch")]
875 Body { generation: u64 },
876 }
877 let Wire::Body { generation } = Wire::deserialize(decoder)?;
878 Ok(Self::new(generation))
879 }
880}
881
882#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
887#[serde(tag = "op")]
888pub enum ClientControlPush {
889 #[serde(rename = "route.closing")]
890 RouteClosing {
891 module_id: String,
892 #[serde(default)]
895 channels: Vec<u16>,
896 reason: RouteCloseReason,
897 },
898 #[serde(rename = "route.closed")]
899 RouteClosed {
900 module_id: String,
901 #[serde(default)]
904 channels: Vec<u16>,
905 reason: RouteCloseReason,
906 drained: bool,
908 abandoned: u32,
911 #[serde(default)]
913 excluded_subscriptions: u32,
914 #[serde(default, skip_serializing_if = "Option::is_none")]
920 terminal: Option<bool>,
921 },
922}
923
924#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
926pub struct SpawnCursor {
927 pub daemon_incarnation: String,
928 pub seq: u64,
929}
930
931#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
933pub struct LiveSpawn {
934 pub module_id: String,
935 pub spawn_generation: u64,
941 pub pid: u32,
942 pub spawned_at_ms: u64,
943}
944
945#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
947pub struct SpawnSnapshot {
948 pub cursor: SpawnCursor,
949 pub ring_bound: u64,
951 pub live: Vec<LiveSpawn>,
952}
953
954#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
956#[serde(rename_all = "snake_case")]
957pub enum SpawnEventKind {
958 Spawned,
959 Exited,
960}
961
962#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
968pub struct SpawnEvent {
969 pub cursor: SpawnCursor,
970 pub kind: SpawnEventKind,
971 pub module_id: String,
972 pub spawn_generation: u64,
974 pub pid: u32,
975 #[serde(default, skip_serializing_if = "Option::is_none")]
976 pub exit_code: Option<i32>,
977 #[serde(default, skip_serializing_if = "Option::is_none")]
978 pub exit_signal: Option<i32>,
979}
980
981#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
983pub struct StderrTail {
984 pub capture: StderrCaptureState,
985 pub entries: Vec<StderrTailEntry>,
986 #[serde(default, skip_serializing_if = "is_zero_u64")]
995 pub dropped_lines: u64,
996}
997
998#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1000pub struct SupervisorRouteModule {
1001 pub module_id: String,
1002 pub routes: Vec<SupervisorRoute>,
1003}
1004
1005#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1007pub struct SupervisorRoute {
1008 pub consumer: SupervisorRouteConsumer,
1009 pub age_ms: u64,
1011 pub draining: bool,
1014 #[serde(default, skip_serializing_if = "Option::is_none")]
1020 pub drain_reason: Option<RouteCloseReason>,
1021 #[serde(default, skip_serializing_if = "Option::is_none")]
1023 pub opener: Option<SupervisorRouteOpener>,
1024}
1025
1026#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1028pub struct SupervisorRouteOpener {
1029 pub connection_id: u64,
1030 pub transport: SupervisorRouteTransport,
1031 #[serde(default, skip_serializing_if = "Option::is_none")]
1032 pub pid: Option<u32>,
1033 #[serde(default, skip_serializing_if = "Option::is_none")]
1034 pub command: Option<String>,
1035}
1036
1037#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1039#[serde(rename_all = "snake_case")]
1040pub enum SupervisorRouteTransport {
1041 Local,
1042 Tcp,
1043}
1044
1045#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1047pub struct SupervisorModuleProvenance {
1048 pub module_id: String,
1049 pub module_declared: ModuleDeclaredProvenance,
1050 pub daemon_observed: SupervisorObservedProcess,
1051}
1052
1053#[non_exhaustive]
1056#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1057pub struct SupervisorModuleProvenanceExt {
1058 #[serde(default, skip_serializing_if = "Option::is_none")]
1060 pub registration: Option<RegistrationMethod>,
1061 #[serde(default, skip_serializing_if = "Option::is_none")]
1065 pub registration_declaration: Option<String>,
1066}
1067
1068impl SupervisorModuleProvenanceExt {
1069 pub fn new() -> Self {
1070 Self::default()
1071 }
1072
1073 #[must_use]
1074 pub fn with_registration(mut self, registration: Option<RegistrationMethod>) -> Self {
1075 self.registration = registration;
1076 self
1077 }
1078
1079 pub fn read_from(entry: &serde_json::Value) -> serde_json::Result<Self> {
1081 if !entry.is_object() {
1082 return Err(serde_json::Error::custom(
1083 "expected a module provenance entry object",
1084 ));
1085 }
1086 serde_json::from_value(entry.clone())
1087 }
1088
1089 pub fn write_to(&self, entry: &mut serde_json::Value) -> serde_json::Result<()> {
1092 let object = entry.as_object_mut().ok_or_else(|| {
1093 serde_json::Error::custom("expected a module provenance entry object")
1094 })?;
1095 object.remove("registration");
1096 if let Some(method) = &self.registration {
1097 object.insert("registration".into(), serde_json::to_value(method)?);
1098 }
1099 object.remove("registration_declaration");
1100 if let Some(declaration) = &self.registration_declaration {
1101 object.insert(
1102 "registration_declaration".into(),
1103 declaration.clone().into(),
1104 );
1105 }
1106 Ok(())
1107 }
1108}
1109
1110#[non_exhaustive]
1113#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1114#[serde(rename_all = "snake_case")]
1115pub enum RegistrationMethod {
1116 Channel,
1117 Nonce,
1118 #[serde(other)]
1119 Unknown,
1120}
1121
1122pub const REGISTRATION_CHANNEL_UNSUPPORTED: &str = "registration_channel_unsupported";
1125
1126#[derive(Debug, Clone, PartialEq)]
1128pub enum ModuleDeclaredProvenance {
1129 Reported {
1130 build: ManifestProvenance,
1131 },
1132 Unverifiable,
1133 Unknown {
1136 tag: String,
1137 body: OrderedJsonObject,
1138 },
1139}
1140
1141#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1146pub struct SupervisorObservedProcess {
1147 #[serde(default, skip_serializing_if = "Option::is_none")]
1153 pub launch_nonce_source: Option<String>,
1154 #[serde(default, skip_serializing_if = "Option::is_none")]
1155 pub pid: Option<u32>,
1156 #[serde(default, skip_serializing_if = "Option::is_none")]
1157 pub spawned_at_ms: Option<u64>,
1158 #[serde(default, skip_serializing_if = "Option::is_none")]
1159 pub spawned_from: Option<PathBuf>,
1160 pub running_image: RunningImageAgreement,
1161}
1162
1163#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1180#[non_exhaustive]
1181pub struct PendingReloadVerdict {
1182 pub path: ReloadPathAgreement,
1183 pub image: RunningImageAgreement,
1184 #[serde(default, skip_serializing_if = "Option::is_none")]
1185 pub spec: Option<LaunchSpecAgreement>,
1186}
1187
1188impl PendingReloadVerdict {
1189 #[must_use]
1191 pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
1192 Self {
1193 path,
1194 image,
1195 spec: None,
1196 }
1197 }
1198
1199 #[must_use]
1201 pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
1202 self.spec = spec;
1203 self
1204 }
1205}
1206
1207#[cfg(test)]
1208mod launch_spec_wire_tests {
1209 use super::*;
1210
1211 #[test]
1212 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
1213 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
1214 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
1215 assert_eq!(parsed.spec, None);
1216 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
1217 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
1218 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
1219 assert!(
1220 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
1221 );
1222 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
1223 let unavailable = LaunchSpecAgreement::Unavailable {
1224 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
1225 };
1226 let encoded = serde_json::to_string(&unavailable).unwrap();
1227 assert_eq!(
1228 encoded,
1229 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
1230 );
1231 assert_eq!(
1232 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
1233 unavailable
1234 );
1235 }
1236}
1237
1238#[derive(Debug, Clone, PartialEq)]
1241pub enum LaunchSpecAgreement {
1242 Match,
1243 Mismatch,
1244 Unavailable {
1245 reason: LaunchSpecUnavailableReason,
1246 },
1247 Unknown {
1248 tag: String,
1249 body: OrderedJsonObject,
1250 },
1251}
1252
1253open_string_enum! {
1254 LaunchSpecUnavailableReason {
1255 NotRunning => "not_running",
1256 SpawnedSpecUnavailable => "spawned_spec_unavailable",
1257 }
1258}
1259
1260#[derive(Debug, Clone, PartialEq)]
1262pub enum ReloadPathAgreement {
1263 Match,
1264 Mismatch {
1265 configured: PathBuf,
1266 spawned_from: PathBuf,
1267 },
1268 Unavailable {
1269 reason: ReloadPathUnavailableReason,
1270 },
1271 Unknown {
1272 tag: String,
1273 body: OrderedJsonObject,
1274 },
1275}
1276
1277open_string_enum! {
1278 ReloadPathUnavailableReason {
1280 NotRunning => "not_running",
1281 SpawnedPathUnavailable => "spawned_path_unavailable",
1282 }
1283}
1284
1285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1287pub struct SupervisorDaemonProvenance {
1288 pub daemon_build: DaemonBuildProvenance,
1289 pub daemon_observed: DaemonObservedProcess,
1290}
1291
1292#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1294pub struct DaemonBuildProvenance {
1295 #[serde(default, skip_serializing_if = "Option::is_none")]
1296 pub build_git_sha: Option<String>,
1297 #[serde(default, skip_serializing_if = "Option::is_none")]
1298 pub build_lock_digest: Option<String>,
1299}
1300
1301#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1303pub struct DaemonObservedProcess {
1304 #[serde(default, skip_serializing_if = "Option::is_none")]
1305 pub pid: Option<u32>,
1306 #[serde(default, skip_serializing_if = "Option::is_none")]
1311 pub started_at_ms: Option<u64>,
1312 pub running_image: RunningImageAgreement,
1313}
1314
1315#[derive(Debug, Clone, PartialEq)]
1317pub enum RunningImageAgreement {
1318 Match {
1319 evidence: RunningImageEvidence,
1320 },
1321 Mismatch {
1322 running: RunningImageEvidence,
1323 disk: RunningImageEvidence,
1324 },
1325 Unavailable {
1326 reason: RunningImageUnavailableReason,
1327 },
1328 Unknown {
1331 tag: String,
1332 body: OrderedJsonObject,
1333 },
1334}
1335
1336#[derive(Debug, Clone, PartialEq)]
1338pub enum RunningImageEvidence {
1339 LinuxProcSha256 {
1340 digest: String,
1341 },
1342 MacosSpawnInode {
1343 device: u64,
1344 inode: u64,
1345 },
1346 WindowsSpawnFileId {
1348 volume_serial_number: u64,
1349 file_id: [u8; 16],
1350 },
1351 Unknown {
1354 tag: String,
1355 body: OrderedJsonObject,
1356 },
1357}
1358
1359open_string_enum! {
1360 RunningImageUnavailableReason {
1362 NotRunning => "not_running",
1363 NotYetMeasured => "not_yet_measured",
1364 UnsupportedPlatform => "unsupported_platform",
1365 RunningExecutableUnreadable => "running_executable_unreadable",
1366 RunningExecutablePermissionDenied => "running_executable_permission_denied",
1367 ProcessHidden => "process_hidden",
1368 SpawnedPathUnreadable => "spawned_path_unreadable",
1369 HashFailed => "hash_failed",
1370 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
1371 }
1372}
1373
1374#[derive(Debug, Clone, PartialEq)]
1380pub enum SupervisorRouteConsumer {
1381 Reserved {
1382 module_id: String,
1383 },
1384 Direct {
1385 connection_id: u64,
1386 },
1387 Unknown {
1390 tag: String,
1391 body: OrderedJsonObject,
1392 },
1393}
1394
1395#[derive(Debug, Clone, PartialEq)]
1402pub enum StderrCaptureState {
1403 Captured,
1406 Incomplete { reason: String },
1408 NotCaptured { reason: String },
1410 Unknown {
1413 tag: String,
1414 body: OrderedJsonObject,
1415 },
1416}
1417
1418#[derive(Debug, Clone, PartialEq)]
1419pub enum StderrTailEntry {
1420 Line {
1421 text: String,
1422 truncated: bool,
1427 at_ms: Option<u64>,
1431 },
1432 ProcessStart,
1437 Unknown {
1440 tag: String,
1441 body: OrderedJsonObject,
1442 },
1443}
1444
1445#[derive(Debug, Serialize, Deserialize)]
1446#[serde(tag = "status", rename_all = "snake_case")]
1447enum ModuleDeclaredProvenanceWire {
1448 Reported { build: ManifestProvenance },
1449 Unverifiable,
1450}
1451
1452#[derive(Debug, Serialize, Deserialize)]
1453#[serde(tag = "status", rename_all = "snake_case")]
1454enum RunningImageAgreementWire {
1455 Match {
1456 evidence: RunningImageEvidence,
1457 },
1458 Mismatch {
1459 running: RunningImageEvidence,
1460 disk: RunningImageEvidence,
1461 },
1462 Unavailable {
1463 reason: RunningImageUnavailableReason,
1464 },
1465}
1466
1467#[derive(Debug, Serialize, Deserialize)]
1468#[serde(tag = "status", rename_all = "snake_case")]
1469enum ReloadPathAgreementWire {
1470 Match,
1471 Mismatch {
1472 configured: PathBuf,
1473 spawned_from: PathBuf,
1474 },
1475 Unavailable {
1476 reason: ReloadPathUnavailableReason,
1477 },
1478}
1479
1480#[derive(Debug, Serialize, Deserialize)]
1481#[serde(tag = "status", rename_all = "snake_case")]
1482enum LaunchSpecAgreementWire {
1483 Match,
1484 Mismatch,
1485 Unavailable { reason: LaunchSpecUnavailableReason },
1486}
1487
1488#[derive(Debug, Serialize, Deserialize)]
1489#[serde(tag = "method", rename_all = "snake_case")]
1490enum RunningImageEvidenceWire {
1491 LinuxProcSha256 {
1492 digest: String,
1493 },
1494 MacosSpawnInode {
1495 device: u64,
1496 inode: u64,
1497 },
1498 WindowsSpawnFileId {
1499 volume_serial_number: u64,
1500 file_id: [u8; 16],
1501 },
1502}
1503
1504#[derive(Debug, Serialize, Deserialize)]
1505#[serde(tag = "kind", rename_all = "snake_case")]
1506enum SupervisorRouteConsumerWire {
1507 Reserved { module_id: String },
1508 Direct { connection_id: u64 },
1509}
1510
1511#[derive(Debug, Serialize, Deserialize)]
1512#[serde(tag = "state", rename_all = "snake_case")]
1513enum StderrCaptureStateWire {
1514 Captured,
1515 Incomplete { reason: String },
1516 NotCaptured { reason: String },
1517}
1518
1519#[derive(Debug, Serialize, Deserialize)]
1520#[serde(tag = "status", rename_all = "snake_case")]
1521enum ChildResourceUsageWire {
1522 Measured(ChildResourceReading),
1523 Unavailable {
1524 reason: ChildResourceUnavailableReason,
1525 },
1526}
1527
1528#[derive(Debug, Serialize, Deserialize)]
1529#[serde(tag = "kind", rename_all = "snake_case")]
1530enum StderrTailEntryWire {
1531 Line {
1532 text: String,
1533 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1534 truncated: bool,
1535 #[serde(default, skip_serializing_if = "Option::is_none")]
1538 at_ms: Option<u64>,
1539 },
1540 ProcessStart,
1541}
1542
1543#[derive(Debug, Clone, PartialEq)]
1545pub enum OrderedJsonValue {
1546 Null,
1547 Bool(bool),
1548 Number(serde_json::Number),
1549 String(String),
1550 Array(Vec<Self>),
1551 Object(OrderedJsonObject),
1552}
1553
1554#[derive(Debug, Clone, PartialEq)]
1556pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1557
1558impl OrderedJsonObject {
1559 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1561 &self.0
1562 }
1563
1564 fn into_value(self) -> serde_json::Value {
1565 serde_json::Value::Object(
1566 self.0
1567 .into_iter()
1568 .map(|(key, value)| (key, value.into_value()))
1569 .collect(),
1570 )
1571 }
1572}
1573
1574impl OrderedJsonValue {
1575 fn into_value(self) -> serde_json::Value {
1576 match self {
1577 Self::Null => serde_json::Value::Null,
1578 Self::Bool(value) => serde_json::Value::Bool(value),
1579 Self::Number(value) => serde_json::Value::Number(value),
1580 Self::String(value) => serde_json::Value::String(value),
1581 Self::Array(values) => {
1582 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1583 }
1584 Self::Object(value) => value.into_value(),
1585 }
1586 }
1587}
1588
1589impl Serialize for OrderedJsonValue {
1590 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1591 where
1592 S: Serializer,
1593 {
1594 match self {
1595 Self::Null => serializer.serialize_unit(),
1596 Self::Bool(value) => serializer.serialize_bool(*value),
1597 Self::Number(value) => value.serialize(serializer),
1598 Self::String(value) => serializer.serialize_str(value),
1599 Self::Array(values) => values.serialize(serializer),
1600 Self::Object(value) => value.serialize(serializer),
1601 }
1602 }
1603}
1604
1605impl<'de> Deserialize<'de> for OrderedJsonValue {
1606 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1607 where
1608 D: Deserializer<'de>,
1609 {
1610 struct OrderedValueVisitor;
1611
1612 impl<'de> Visitor<'de> for OrderedValueVisitor {
1613 type Value = OrderedJsonValue;
1614
1615 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1616 formatter.write_str("a JSON value with ordered object members")
1617 }
1618
1619 fn visit_unit<E>(self) -> Result<Self::Value, E>
1620 where
1621 E: serde::de::Error,
1622 {
1623 Ok(OrderedJsonValue::Null)
1624 }
1625
1626 fn visit_none<E>(self) -> Result<Self::Value, E>
1627 where
1628 E: serde::de::Error,
1629 {
1630 Ok(OrderedJsonValue::Null)
1631 }
1632
1633 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1634 where
1635 D: Deserializer<'de>,
1636 {
1637 OrderedJsonValue::deserialize(deserializer)
1638 }
1639
1640 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1641 where
1642 E: serde::de::Error,
1643 {
1644 Ok(OrderedJsonValue::Bool(value))
1645 }
1646
1647 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1648 where
1649 E: serde::de::Error,
1650 {
1651 Ok(OrderedJsonValue::Number(value.into()))
1652 }
1653
1654 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1655 where
1656 E: serde::de::Error,
1657 {
1658 Ok(OrderedJsonValue::Number(value.into()))
1659 }
1660
1661 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1662 where
1663 E: serde::de::Error,
1664 {
1665 serde_json::Number::from_f64(value)
1666 .map(OrderedJsonValue::Number)
1667 .ok_or_else(|| E::custom("non-finite JSON number"))
1668 }
1669
1670 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1671 where
1672 E: serde::de::Error,
1673 {
1674 Ok(OrderedJsonValue::String(value.to_owned()))
1675 }
1676
1677 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1678 where
1679 E: serde::de::Error,
1680 {
1681 Ok(OrderedJsonValue::String(value))
1682 }
1683
1684 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1685 where
1686 A: SeqAccess<'de>,
1687 {
1688 let mut values = Vec::new();
1689 while let Some(value) = sequence.next_element()? {
1690 values.push(value);
1691 }
1692 Ok(OrderedJsonValue::Array(values))
1693 }
1694
1695 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1696 where
1697 A: MapAccess<'de>,
1698 {
1699 let mut entries = Vec::new();
1700 while let Some((key, value)) = map.next_entry()? {
1701 entries.push((key, value));
1702 }
1703 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1704 }
1705 }
1706
1707 deserializer.deserialize_any(OrderedValueVisitor)
1708 }
1709}
1710
1711impl Serialize for OrderedJsonObject {
1712 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1713 where
1714 S: Serializer,
1715 {
1716 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1717 for (key, value) in &self.0 {
1718 map.serialize_entry(key, value)?;
1719 }
1720 map.end()
1721 }
1722}
1723
1724impl<'de> Deserialize<'de> for OrderedJsonObject {
1725 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1726 where
1727 D: Deserializer<'de>,
1728 {
1729 struct OrderedObjectVisitor;
1730
1731 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1732 type Value = OrderedJsonObject;
1733
1734 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1735 formatter.write_str("an object with ordered JSON members")
1736 }
1737
1738 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1739 where
1740 A: MapAccess<'de>,
1741 {
1742 let mut entries = Vec::new();
1743 while let Some((key, value)) = map.next_entry()? {
1744 entries.push((key, value));
1745 }
1746 Ok(OrderedJsonObject(entries))
1747 }
1748 }
1749
1750 deserializer.deserialize_map(OrderedObjectVisitor)
1751 }
1752}
1753
1754fn read_tagged<'de, D>(
1755 deserializer: D,
1756 field: &'static str,
1757) -> Result<(String, OrderedJsonObject), D::Error>
1758where
1759 D: Deserializer<'de>,
1760{
1761 let body = OrderedJsonObject::deserialize(deserializer)?;
1762 let mut tag = None;
1763 for (key, value) in body.as_entries() {
1764 if key != field {
1765 continue;
1766 }
1767 if tag.is_some() {
1768 return Err(D::Error::custom(format!(
1769 "tagged object has duplicate `{field}` field"
1770 )));
1771 }
1772 let OrderedJsonValue::String(value) = value else {
1773 return Err(D::Error::custom(format!(
1774 "tagged object has no string `{field}` field"
1775 )));
1776 };
1777 tag = Some(value);
1778 }
1779 let Some(tag) = tag else {
1780 return Err(D::Error::custom(format!(
1781 "tagged object has no string `{field}` field"
1782 )));
1783 };
1784 Ok((tag.to_string(), body))
1785}
1786
1787fn read_ordered_tagged(
1788 value: OrderedJsonValue,
1789 field: &'static str,
1790) -> Result<(String, OrderedJsonObject), String> {
1791 let OrderedJsonValue::Object(body) = value else {
1792 return Err(format!("expected tagged object with `{field}` field"));
1793 };
1794 let mut tag = None;
1795 for (key, value) in body.as_entries() {
1796 if key != field {
1797 continue;
1798 }
1799 if tag.is_some() {
1800 return Err(format!("tagged object has duplicate `{field}` field"));
1801 }
1802 let OrderedJsonValue::String(value) = value else {
1803 return Err(format!("tagged object has no string `{field}` field"));
1804 };
1805 tag = Some(value);
1806 }
1807 let Some(tag) = tag else {
1808 return Err(format!("tagged object has no string `{field}` field"));
1809 };
1810 Ok((tag.to_string(), body))
1811}
1812
1813fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1814 body.as_entries()
1815 .iter()
1816 .find_map(|(key, value)| (key == field).then_some(value))
1817}
1818
1819fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1820 match ordered_field(body, field) {
1821 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1822 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1823 None => Err(format!("tagged object has no `{field}` field")),
1824 }
1825}
1826
1827fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1828 let (tag, body) = read_ordered_tagged(value, "method")?;
1829 match tag.as_str() {
1830 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1831 digest: ordered_string(&body, "digest")?,
1832 }),
1833 "macos_spawn_inode" => {
1834 let device = ordered_field(&body, "device")
1835 .and_then(|value| match value {
1836 OrderedJsonValue::Number(number) => number.as_u64(),
1837 _ => None,
1838 })
1839 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1840 let inode = ordered_field(&body, "inode")
1841 .and_then(|value| match value {
1842 OrderedJsonValue::Number(number) => number.as_u64(),
1843 _ => None,
1844 })
1845 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1846 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1847 }
1848 "windows_spawn_file_id" => {
1849 let wire: RunningImageEvidenceWire = serde_json::from_value(
1850 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1851 )
1852 .map_err(|error| error.to_string())?;
1853 match wire {
1854 RunningImageEvidenceWire::WindowsSpawnFileId {
1855 volume_serial_number,
1856 file_id,
1857 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1858 volume_serial_number,
1859 file_id,
1860 }),
1861 _ => unreachable!(),
1862 }
1863 }
1864 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1865 }
1866}
1867
1868impl Serialize for ModuleDeclaredProvenance {
1869 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1870 where
1871 S: Serializer,
1872 {
1873 match self {
1874 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1875 build: build.clone(),
1876 }
1877 .serialize(serializer),
1878 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1879 Self::Unknown { body, .. } => body.serialize(serializer),
1880 }
1881 }
1882}
1883
1884impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1885 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1886 where
1887 D: serde::Deserializer<'de>,
1888 {
1889 let (tag, value) = read_tagged(deserializer, "status")?;
1890 match tag.as_str() {
1891 "reported" => match serde_json::from_value(value.into_value())
1892 .map_err(D::Error::custom)?
1893 {
1894 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1895 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1896 },
1897 "unverifiable" => {
1898 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1899 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1900 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1901 }
1902 }
1903 _ => Ok(Self::Unknown { tag, body: value }),
1904 }
1905 }
1906}
1907
1908impl Serialize for RunningImageAgreement {
1909 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1910 where
1911 S: Serializer,
1912 {
1913 match self {
1914 Self::Match { evidence } => RunningImageAgreementWire::Match {
1915 evidence: evidence.clone(),
1916 }
1917 .serialize(serializer),
1918 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1919 running: running.clone(),
1920 disk: disk.clone(),
1921 }
1922 .serialize(serializer),
1923 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1924 reason: reason.clone(),
1925 }
1926 .serialize(serializer),
1927 Self::Unknown { body, .. } => body.serialize(serializer),
1928 }
1929 }
1930}
1931
1932impl Serialize for ReloadPathAgreement {
1933 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1934 where
1935 S: Serializer,
1936 {
1937 match self {
1938 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1939 Self::Mismatch {
1940 configured,
1941 spawned_from,
1942 } => ReloadPathAgreementWire::Mismatch {
1943 configured: configured.clone(),
1944 spawned_from: spawned_from.clone(),
1945 }
1946 .serialize(serializer),
1947 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1948 reason: reason.clone(),
1949 }
1950 .serialize(serializer),
1951 Self::Unknown { body, .. } => body.serialize(serializer),
1952 }
1953 }
1954}
1955
1956impl Serialize for LaunchSpecAgreement {
1957 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1958 where
1959 S: Serializer,
1960 {
1961 match self {
1962 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1963 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1964 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1965 reason: reason.clone(),
1966 }
1967 .serialize(serializer),
1968 Self::Unknown { body, .. } => body.serialize(serializer),
1969 }
1970 }
1971}
1972
1973impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1974 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1975 where
1976 D: Deserializer<'de>,
1977 {
1978 let (tag, body) = read_tagged(deserializer, "status")?;
1979 match tag.as_str() {
1980 "match" => Ok(Self::Match),
1981 "mismatch" => Ok(Self::Mismatch),
1982 "unavailable" => match serde_json::from_value(body.into_value())
1983 .map_err(D::Error::custom)?
1984 {
1985 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1986 _ => unreachable!(),
1987 },
1988 _ => Ok(Self::Unknown { tag, body }),
1989 }
1990 }
1991}
1992
1993impl<'de> Deserialize<'de> for ReloadPathAgreement {
1994 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1995 where
1996 D: Deserializer<'de>,
1997 {
1998 let (tag, body) = read_tagged(deserializer, "status")?;
1999 match tag.as_str() {
2000 "match" => Ok(Self::Match),
2001 "mismatch" => {
2002 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2003 ReloadPathAgreementWire::Mismatch {
2004 configured,
2005 spawned_from,
2006 } => Ok(Self::Mismatch {
2007 configured,
2008 spawned_from,
2009 }),
2010 _ => unreachable!(),
2011 }
2012 }
2013 "unavailable" => match serde_json::from_value(body.into_value())
2014 .map_err(D::Error::custom)?
2015 {
2016 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
2017 _ => unreachable!(),
2018 },
2019 _ => Ok(Self::Unknown { tag, body }),
2020 }
2021 }
2022}
2023
2024impl<'de> Deserialize<'de> for RunningImageAgreement {
2025 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2026 where
2027 D: serde::Deserializer<'de>,
2028 {
2029 let (tag, value) = read_tagged(deserializer, "status")?;
2030 match tag.as_str() {
2031 "match" => Ok(Self::Match {
2032 evidence: decode_running_image_evidence(
2033 ordered_field(&value, "evidence")
2034 .cloned()
2035 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
2036 )
2037 .map_err(D::Error::custom)?,
2038 }),
2039 "mismatch" => Ok(Self::Mismatch {
2040 running: decode_running_image_evidence(
2041 ordered_field(&value, "running")
2042 .cloned()
2043 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
2044 )
2045 .map_err(D::Error::custom)?,
2046 disk: decode_running_image_evidence(
2047 ordered_field(&value, "disk")
2048 .cloned()
2049 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
2050 )
2051 .map_err(D::Error::custom)?,
2052 }),
2053 "unavailable" => Ok(Self::Unavailable {
2054 reason: serde_json::from_value(
2055 ordered_field(&value, "reason")
2056 .cloned()
2057 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
2058 .into_value(),
2059 )
2060 .map_err(D::Error::custom)?,
2061 }),
2062 _ => Ok(Self::Unknown { tag, body: value }),
2063 }
2064 }
2065}
2066
2067impl Serialize for ChildResourceUsage {
2068 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2069 where
2070 S: Serializer,
2071 {
2072 match self {
2073 Self::Measured(reading) => {
2074 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
2075 }
2076 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
2077 reason: reason.clone(),
2078 }
2079 .serialize(serializer),
2080 Self::Unknown { body, .. } => body.serialize(serializer),
2081 }
2082 }
2083}
2084
2085impl<'de> Deserialize<'de> for ChildResourceUsage {
2086 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2087 where
2088 D: Deserializer<'de>,
2089 {
2090 let (tag, body) = read_tagged(deserializer, "status")?;
2091 match tag.as_str() {
2092 "measured" | "unavailable" => {
2093 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2094 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
2095 ChildResourceUsageWire::Unavailable { reason } => {
2096 Ok(Self::Unavailable { reason })
2097 }
2098 }
2099 }
2100 _ => Ok(Self::Unknown { tag, body }),
2101 }
2102 }
2103}
2104
2105impl Serialize for RunningImageEvidence {
2106 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2107 where
2108 S: Serializer,
2109 {
2110 match self {
2111 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
2112 digest: digest.clone(),
2113 }
2114 .serialize(serializer),
2115 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
2116 device: *device,
2117 inode: *inode,
2118 }
2119 .serialize(serializer),
2120 Self::WindowsSpawnFileId {
2121 volume_serial_number,
2122 file_id,
2123 } => RunningImageEvidenceWire::WindowsSpawnFileId {
2124 volume_serial_number: *volume_serial_number,
2125 file_id: *file_id,
2126 }
2127 .serialize(serializer),
2128 Self::Unknown { body, .. } => body.serialize(serializer),
2129 }
2130 }
2131}
2132
2133impl<'de> Deserialize<'de> for RunningImageEvidence {
2134 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2135 where
2136 D: serde::Deserializer<'de>,
2137 {
2138 let (tag, value) = read_tagged(deserializer, "method")?;
2139 match tag.as_str() {
2140 "linux_proc_sha256" => {
2141 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2142 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
2143 Ok(Self::LinuxProcSha256 { digest })
2144 }
2145 _ => unreachable!(),
2146 }
2147 }
2148 "macos_spawn_inode" => {
2149 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2150 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
2151 Ok(Self::MacosSpawnInode { device, inode })
2152 }
2153 _ => unreachable!(),
2154 }
2155 }
2156 "windows_spawn_file_id" => {
2157 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2158 RunningImageEvidenceWire::WindowsSpawnFileId {
2159 volume_serial_number,
2160 file_id,
2161 } => Ok(Self::WindowsSpawnFileId {
2162 volume_serial_number,
2163 file_id,
2164 }),
2165 _ => unreachable!(),
2166 }
2167 }
2168 _ => Ok(Self::Unknown { tag, body: value }),
2169 }
2170 }
2171}
2172
2173impl Serialize for SupervisorRouteConsumer {
2174 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2175 where
2176 S: Serializer,
2177 {
2178 match self {
2179 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
2180 module_id: module_id.clone(),
2181 }
2182 .serialize(serializer),
2183 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
2184 connection_id: *connection_id,
2185 }
2186 .serialize(serializer),
2187 Self::Unknown { body, .. } => body.serialize(serializer),
2188 }
2189 }
2190}
2191
2192impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
2193 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2194 where
2195 D: serde::Deserializer<'de>,
2196 {
2197 let (tag, value) = read_tagged(deserializer, "kind")?;
2198 match tag.as_str() {
2199 "reserved" => {
2200 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2201 SupervisorRouteConsumerWire::Reserved { module_id } => {
2202 Ok(Self::Reserved { module_id })
2203 }
2204 _ => unreachable!(),
2205 }
2206 }
2207 "direct" => {
2208 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2209 SupervisorRouteConsumerWire::Direct { connection_id } => {
2210 Ok(Self::Direct { connection_id })
2211 }
2212 _ => unreachable!(),
2213 }
2214 }
2215 _ => Ok(Self::Unknown { tag, body: value }),
2216 }
2217 }
2218}
2219
2220impl Serialize for StderrCaptureState {
2221 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2222 where
2223 S: Serializer,
2224 {
2225 match self {
2226 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
2227 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
2228 reason: reason.clone(),
2229 }
2230 .serialize(serializer),
2231 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
2232 reason: reason.clone(),
2233 }
2234 .serialize(serializer),
2235 Self::Unknown { body, .. } => body.serialize(serializer),
2236 }
2237 }
2238}
2239
2240impl<'de> Deserialize<'de> for StderrCaptureState {
2241 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2242 where
2243 D: serde::Deserializer<'de>,
2244 {
2245 let (tag, value) = read_tagged(deserializer, "state")?;
2246 match tag.as_str() {
2247 "captured" => {
2248 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2249 StderrCaptureStateWire::Captured => Ok(Self::Captured),
2250 _ => unreachable!(),
2251 }
2252 }
2253 "incomplete" => match serde_json::from_value(value.into_value())
2254 .map_err(D::Error::custom)?
2255 {
2256 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
2257 _ => unreachable!(),
2258 },
2259 "not_captured" => match serde_json::from_value(value.into_value())
2260 .map_err(D::Error::custom)?
2261 {
2262 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
2263 _ => unreachable!(),
2264 },
2265 _ => Ok(Self::Unknown { tag, body: value }),
2266 }
2267 }
2268}
2269
2270impl Serialize for StderrTailEntry {
2271 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2272 where
2273 S: Serializer,
2274 {
2275 match self {
2276 Self::Line {
2277 text,
2278 truncated,
2279 at_ms,
2280 } => StderrTailEntryWire::Line {
2281 text: text.clone(),
2282 truncated: *truncated,
2283 at_ms: *at_ms,
2284 }
2285 .serialize(serializer),
2286 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
2287 Self::Unknown { body, .. } => body.serialize(serializer),
2288 }
2289 }
2290}
2291
2292impl<'de> Deserialize<'de> for StderrTailEntry {
2293 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2294 where
2295 D: serde::Deserializer<'de>,
2296 {
2297 let (tag, value) = read_tagged(deserializer, "kind")?;
2298 match tag.as_str() {
2299 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2300 StderrTailEntryWire::Line {
2301 text,
2302 truncated,
2303 at_ms,
2304 } => Ok(Self::Line {
2305 text,
2306 truncated,
2307 at_ms,
2308 }),
2309 _ => unreachable!(),
2310 },
2311 "process_start" => {
2312 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2313 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
2314 _ => unreachable!(),
2315 }
2316 }
2317 _ => Ok(Self::Unknown { tag, body: value }),
2318 }
2319 }
2320}
2321
2322fn is_zero_u64(value: &u64) -> bool {
2323 *value == 0
2324}
2325
2326fn default_true() -> bool {
2327 true
2328}
2329
2330#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2332pub struct TerminalHistory {
2333 pub daemon_started_at_ms: u64,
2335 pub entries: Vec<TerminalEntry>,
2336 #[serde(default, skip_serializing_if = "is_zero_u64")]
2339 pub dropped: u64,
2340 #[serde(default, skip_serializing_if = "is_zero_u64")]
2343 pub journal_skipped_lines: u64,
2344 #[serde(default, skip_serializing_if = "is_zero_u64")]
2346 pub journal_read_errors: u64,
2347 #[serde(default, skip_serializing_if = "is_zero_u64")]
2349 pub journal_write_failures: u64,
2350}
2351
2352#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2354pub struct TerminalEntry {
2355 #[serde(default, skip_serializing_if = "Option::is_none")]
2358 pub daemon_incarnation: Option<String>,
2359 #[serde(default, skip_serializing_if = "Option::is_none")]
2360 pub exit_code: Option<i32>,
2361 #[serde(default, skip_serializing_if = "Option::is_none")]
2362 pub exit_signal: Option<i32>,
2363 pub at_ms: u64,
2364 pub disposition: TerminalDisposition,
2365 #[serde(default, skip_serializing_if = "Option::is_none")]
2369 pub exit_kind: Option<TerminalExitKind>,
2370 #[serde(default, skip_serializing_if = "Option::is_none")]
2377 pub disposition_detail: Option<String>,
2378}
2379
2380#[derive(Debug, Clone, PartialEq, Eq)]
2385pub enum TerminalExitKind {
2386 Clean,
2387 Crash,
2388 DeliberateSeverance,
2389 Unknown(String),
2390}
2391
2392impl TerminalExitKind {
2393 fn wire_name(&self) -> &str {
2394 match self {
2395 Self::Clean => "clean",
2396 Self::Crash => "crash",
2397 Self::DeliberateSeverance => "deliberate_severance",
2398 Self::Unknown(value) => value,
2399 }
2400 }
2401}
2402
2403impl Serialize for TerminalExitKind {
2404 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2405 where
2406 S: serde::Serializer,
2407 {
2408 serializer.serialize_str(self.wire_name())
2409 }
2410}
2411
2412impl<'de> Deserialize<'de> for TerminalExitKind {
2413 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2414 where
2415 D: serde::Deserializer<'de>,
2416 {
2417 let value = String::deserialize(deserializer)?;
2418 Ok(match value.as_str() {
2419 "clean" => Self::Clean,
2420 "crash" => Self::Crash,
2421 "deliberate_severance" => Self::DeliberateSeverance,
2422 _ => Self::Unknown(value),
2423 })
2424 }
2425}
2426
2427open_string_enum! {
2428 TerminalDisposition {
2430 Stopped => "stopped",
2431 Disabled => "disabled",
2432 Failed => "failed",
2433 Restarting => "restarting",
2434 DaemonShutdown => "daemon_shutdown",
2439 }
2440}
2441
2442#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2443#[serde(rename_all = "snake_case")]
2444pub enum PollKind {
2445 Status,
2446 Liveness,
2447}
2448
2449#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2461#[non_exhaustive]
2462pub struct CatalogEntry {
2463 pub module_id: String,
2464 #[serde(default, skip_serializing_if = "Option::is_none")]
2466 pub display_name: Option<String>,
2467 #[serde(default = "default_true")]
2478 pub ready: bool,
2479 #[serde(default, skip_serializing_if = "Option::is_none")]
2483 pub not_ready: Option<NotReadyReason>,
2484 #[serde(default, skip_serializing_if = "Option::is_none")]
2505 pub module_version: Option<String>,
2506 #[serde(default, skip_serializing_if = "Option::is_none")]
2509 pub provenance: Option<ManifestProvenance>,
2510 pub roles: Vec<ProviderRole>,
2511 pub control_ops: Vec<String>,
2512 #[serde(default, skip_serializing_if = "Option::is_none")]
2517 pub capabilities: Option<CapabilityDeclarations>,
2518 #[serde(default, skip_serializing_if = "Option::is_none")]
2521 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2522 #[serde(default, skip_serializing_if = "Option::is_none")]
2526 pub events: Option<Vec<EventDeclaration>>,
2527 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2530 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2531 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2534 pub operation_payload: BTreeMap<String, OperationPayload>,
2535 #[serde(default, skip_serializing_if = "Option::is_none")]
2541 pub flow_operations: Option<Vec<String>>,
2542 #[serde(default, skip_serializing_if = "Option::is_none")]
2544 pub operation_deferral: Option<BTreeMap<String, bool>>,
2545 #[serde(default, skip_serializing_if = "Option::is_none")]
2551 pub confirm_operations: Option<Vec<String>>,
2552 #[serde(default, skip_serializing_if = "Option::is_none")]
2555 pub rich_ui: Option<RichUiDescriptor>,
2556 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2559 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2560 #[serde(default, skip_serializing_if = "is_false")]
2565 pub nonce_verified: bool,
2566 #[serde(default, skip_serializing_if = "Option::is_none")]
2569 pub incarnation: Option<String>,
2570 #[serde(
2571 default,
2572 skip_serializing_if = "Option::is_none",
2573 deserialize_with = "deserialize_optional_attestation_integer"
2574 )]
2575 pub spawn: Option<u64>,
2576 #[serde(default, skip_serializing_if = "Option::is_none")]
2577 pub first_party: Option<bool>,
2578 #[serde(default, skip_serializing_if = "Option::is_none")]
2579 pub origin: Option<CatalogOrigin>,
2580 #[serde(default, skip_serializing_if = "Option::is_none")]
2581 pub requested_declarations_digest: Option<String>,
2582 #[serde(default, skip_serializing_if = "Option::is_none")]
2583 pub approved_declarations_digest: Option<String>,
2584 #[serde(default, skip_serializing_if = "Option::is_none")]
2587 pub approved_declarations: Option<ProviderDeclarations>,
2588 #[serde(default, skip_serializing_if = "Option::is_none")]
2589 pub requested_declarations: Option<ProviderDeclarations>,
2590}
2591
2592impl CatalogEntry {
2593 #[must_use]
2595 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2596 self.display_name = display_name;
2597 self
2598 }
2599
2600 #[must_use]
2602 pub fn new(
2603 module_id: impl Into<String>,
2604 roles: Vec<ProviderRole>,
2605 control_ops: Vec<String>,
2606 ) -> Self {
2607 Self {
2608 module_id: module_id.into(),
2609 ready: default_true(),
2610 display_name: None,
2611 not_ready: None,
2612 module_version: None,
2613 provenance: None,
2614 roles,
2615 control_ops,
2616 capabilities: None,
2617 self_signals: None,
2618 events: None,
2619 operation_delivery: BTreeMap::new(),
2620 operation_payload: BTreeMap::new(),
2621 flow_operations: None,
2622 operation_deferral: None,
2623 confirm_operations: None,
2624 rich_ui: None,
2625 role_declarations: BTreeMap::new(),
2626 nonce_verified: false,
2627 incarnation: None,
2628 spawn: None,
2629 first_party: None,
2630 origin: None,
2631 requested_declarations_digest: None,
2632 approved_declarations_digest: None,
2633 approved_declarations: None,
2634 requested_declarations: None,
2635 }
2636 }
2637
2638 #[must_use]
2640 pub fn with_operation_payload(
2641 mut self,
2642 operation_payload: BTreeMap<String, OperationPayload>,
2643 ) -> Self {
2644 self.operation_payload = operation_payload;
2645 self
2646 }
2647
2648 #[must_use]
2651 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2652 self.flow_operations = flow_operations;
2653 self
2654 }
2655
2656 #[must_use]
2658 pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
2659 self.operation_deferral = operations;
2660 self
2661 }
2662
2663 #[must_use]
2666 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2667 self.confirm_operations = confirm_operations;
2668 self
2669 }
2670
2671 #[must_use]
2673 pub fn with_ready(mut self, ready: bool) -> Self {
2674 self.ready = ready;
2675 self
2676 }
2677
2678 #[must_use]
2680 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2681 self.not_ready = not_ready;
2682 self
2683 }
2684
2685 #[must_use]
2687 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2688 self.module_version = module_version;
2689 self
2690 }
2691
2692 #[must_use]
2694 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2695 self.provenance = provenance;
2696 self
2697 }
2698
2699 #[must_use]
2701 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2702 self.capabilities = capabilities;
2703 self
2704 }
2705
2706 #[must_use]
2708 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2709 self.self_signals = self_signals;
2710 self
2711 }
2712
2713 #[must_use]
2715 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2716 self.events = events;
2717 self
2718 }
2719
2720 #[must_use]
2723 pub fn with_operation_delivery(
2724 mut self,
2725 operation_delivery: BTreeMap<String, OperationDelivery>,
2726 ) -> Self {
2727 self.operation_delivery = operation_delivery;
2728 self
2729 }
2730
2731 #[must_use]
2733 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2734 self.rich_ui = rich_ui;
2735 self
2736 }
2737
2738 #[must_use]
2740 pub fn with_role_declarations(
2741 mut self,
2742 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2743 ) -> Self {
2744 self.role_declarations = role_declarations;
2745 self
2746 }
2747
2748 #[must_use]
2750 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2751 self.nonce_verified = nonce_verified;
2752 self
2753 }
2754}
2755
2756fn is_false(value: &bool) -> bool {
2757 !value
2758}
2759
2760#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2762pub struct NotReadyReason {
2763 pub reason: String,
2768 #[serde(default, skip_serializing_if = "Option::is_none")]
2771 pub capability: Option<String>,
2772}
2773
2774impl NotReadyReason {
2775 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2776 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2777}
2778
2779#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2780pub struct CapabilityRequirementStatus {
2781 pub consumer: String,
2782 pub capability: String,
2783 pub need: String,
2784 pub verdict: String,
2785 pub episode_seq: u64,
2786 pub config_satisfiable: bool,
2787 pub runtime_available: bool,
2788 pub detail: String,
2789}
2790
2791#[non_exhaustive]
2796#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2797#[serde(rename_all = "snake_case")]
2798pub enum PendingModuleApply {
2799 NextSupervision,
2800 WithNextLaunchOrHealthChange,
2801 DaemonRestart,
2802 ConfigGate,
2803 #[serde(other)]
2804 Other,
2805}
2806
2807#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2809pub struct SupervisorPendingField {
2810 pub field: String,
2811 pub applies: PendingModuleApply,
2812 #[serde(default, skip_serializing_if = "Option::is_none")]
2813 pub value: Option<serde_json::Value>,
2814}
2815
2816#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2817pub struct SupervisorPendingModule {
2818 pub module_id: String,
2819 pub fields: Vec<SupervisorPendingField>,
2820}
2821
2822#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2823pub struct SupervisorRescanResult {
2824 pub added: Vec<String>,
2825 pub removed: Vec<String>,
2826 pub changed_pending_reload: Vec<String>,
2827 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2829 pub changed_pending: Vec<SupervisorPendingModule>,
2830 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2843 pub enabled_changes: Vec<String>,
2844 pub unchanged: u32,
2845 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2853 pub preview: bool,
2854 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2872 pub restart_required: Vec<String>,
2873 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2877 pub capability_warnings: Vec<String>,
2878 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2885 pub module_actions: Vec<RescanModuleAction>,
2886 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2890 pub earlier_pending: Vec<String>,
2891 #[serde(default, skip_serializing_if = "Option::is_none")]
2894 pub expect: Option<RescanExpect>,
2895}
2896
2897#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2913#[serde(rename_all = "snake_case")]
2914pub enum ModuleProtocol {
2915 #[default]
2919 Subc,
2920 None,
2929}
2930
2931#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2943#[non_exhaustive]
2944pub struct SupervisorEntry {
2945 #[serde(default, skip_serializing_if = "Option::is_none")]
2947 pub script: Option<ScriptModuleStatus>,
2948 #[serde(default, skip_serializing_if = "Option::is_none")]
2951 pub waiting_for_previous_pid: Option<u32>,
2952 pub module_id: String,
2953 pub state: String,
2954 #[serde(default, skip_serializing_if = "Option::is_none")]
2958 pub admission_refused: Option<String>,
2959 #[serde(default, skip_serializing_if = "Option::is_none")]
2963 pub next_retry_at_ms: Option<u64>,
2964 pub enabled: bool,
2965 #[serde(default, skip_serializing_if = "Option::is_none")]
2968 pub configured_enabled: Option<bool>,
2969 pub live: bool,
2979 #[serde(default)]
2983 pub protocol: ModuleProtocol,
2984 #[serde(default, skip_serializing_if = "Option::is_none")]
2987 pub launch_nonce_env: Option<bool>,
2988 #[serde(default, skip_serializing_if = "Option::is_none")]
2994 pub launch_nonce_source: Option<String>,
2995 pub health: SupervisorHealthStatus,
2996 #[serde(default, skip_serializing_if = "Option::is_none")]
2999 pub pending_reload: Option<PendingReloadVerdict>,
3000 #[serde(default)]
3006 pub last_probe_ms: Option<u64>,
3007 #[serde(default, skip_serializing_if = "Option::is_none")]
3011 pub last_exit_code: Option<i32>,
3012 #[serde(default, skip_serializing_if = "Option::is_none")]
3016 pub last_exit_signal: Option<i32>,
3017 #[serde(default, skip_serializing_if = "Option::is_none")]
3021 pub last_exit_ms: Option<u64>,
3022 #[serde(default, skip_serializing_if = "Option::is_none")]
3025 pub last_exit_kind: Option<TerminalExitKind>,
3026 #[serde(default, skip_serializing_if = "Option::is_none")]
3043 pub restart_count: Option<u32>,
3044 #[serde(default, skip_serializing_if = "Option::is_none")]
3047 pub max_restarts: Option<u32>,
3048 #[serde(default, skip_serializing_if = "Option::is_none")]
3051 pub lifetime_restarts: Option<u32>,
3052 #[serde(default, skip_serializing_if = "Option::is_none")]
3056 pub spawn_generation: Option<u64>,
3057 #[serde(default, skip_serializing_if = "Option::is_none")]
3067 pub restart_window_secs: Option<u64>,
3068 #[serde(default, skip_serializing_if = "Option::is_none")]
3072 pub drain_timeout_ms: Option<u64>,
3073 #[serde(default, skip_serializing_if = "Option::is_none")]
3076 pub restart_backoff_ms: Option<u64>,
3077 #[serde(default, skip_serializing_if = "Option::is_none")]
3080 pub restart_max_backoff_ms: Option<u64>,
3081 #[serde(default, skip_serializing_if = "Option::is_none")]
3094 pub resources: Option<ChildResourceUsage>,
3095 #[serde(default, skip_serializing_if = "Option::is_none")]
3097 pub tree: Option<TreeReading>,
3098 #[serde(default, skip_serializing_if = "Option::is_none")]
3104 pub tree_unavailable: Option<String>,
3105 #[serde(default, skip_serializing_if = "Option::is_none")]
3107 pub cpu_last_hour: Option<CpuLastHour>,
3108 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3110 pub pending: Vec<SupervisorPendingField>,
3111}
3112
3113impl SupervisorEntry {
3114 #[must_use]
3115 pub fn with_script(mut self, script: Option<ScriptModuleStatus>) -> Self {
3116 self.script = script;
3117 self
3118 }
3119 #[must_use]
3121 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3122 self.next_retry_at_ms = next_retry_at_ms;
3123 self
3124 }
3125
3126 #[must_use]
3128 pub fn new(
3129 module_id: impl Into<String>,
3130 state: impl Into<String>,
3131 enabled: bool,
3132 live: bool,
3133 health: SupervisorHealthStatus,
3134 ) -> Self {
3135 Self {
3136 module_id: module_id.into(),
3137 script: None,
3138 state: state.into(),
3139 admission_refused: None,
3140 next_retry_at_ms: None,
3141 waiting_for_previous_pid: None,
3142 enabled,
3143 configured_enabled: None,
3144 live,
3145 protocol: ModuleProtocol::default(),
3146 launch_nonce_env: None,
3147 launch_nonce_source: None,
3148 health,
3149 pending_reload: None,
3150 last_probe_ms: None,
3151 last_exit_code: None,
3152 last_exit_signal: None,
3153 last_exit_ms: None,
3154 last_exit_kind: None,
3155 restart_count: None,
3156 max_restarts: None,
3157 lifetime_restarts: None,
3158 spawn_generation: None,
3159 restart_window_secs: None,
3160 drain_timeout_ms: None,
3161 restart_backoff_ms: None,
3162 restart_max_backoff_ms: None,
3163 resources: None,
3164 tree: None,
3165 tree_unavailable: None,
3166 cpu_last_hour: None,
3167 pending: Vec::new(),
3168 }
3169 }
3170
3171 #[must_use]
3173 pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3174 self.admission_refused = reason;
3175 self
3176 }
3177
3178 #[must_use]
3180 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3181 self.protocol = protocol;
3182 self
3183 }
3184
3185 #[must_use]
3187 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3188 self.configured_enabled = configured_enabled;
3189 self
3190 }
3191
3192 #[must_use]
3194 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3195 self.launch_nonce_env = launch_nonce_env;
3196 self
3197 }
3198
3199 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3200 self.launch_nonce_source = source;
3201 self
3202 }
3203
3204 #[must_use]
3205 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3206 self.waiting_for_previous_pid = pid;
3207 self
3208 }
3209
3210 #[must_use]
3212 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3213 self.pending_reload = pending_reload;
3214 self
3215 }
3216
3217 #[must_use]
3219 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3220 self.last_probe_ms = last_probe_ms;
3221 self
3222 }
3223
3224 #[must_use]
3226 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3227 self.last_exit_code = last_exit_code;
3228 self
3229 }
3230
3231 #[must_use]
3233 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3234 self.last_exit_signal = last_exit_signal;
3235 self
3236 }
3237
3238 #[must_use]
3240 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3241 self.last_exit_ms = last_exit_ms;
3242 self
3243 }
3244
3245 #[must_use]
3247 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3248 self.last_exit_kind = last_exit_kind;
3249 self
3250 }
3251
3252 #[must_use]
3254 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3255 self.restart_count = restart_count;
3256 self
3257 }
3258
3259 #[must_use]
3261 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3262 self.max_restarts = max_restarts;
3263 self
3264 }
3265
3266 #[must_use]
3268 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3269 self.lifetime_restarts = lifetime_restarts;
3270 self
3271 }
3272
3273 #[must_use]
3275 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3276 self.spawn_generation = spawn_generation;
3277 self
3278 }
3279
3280 #[must_use]
3282 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3283 self.restart_window_secs = restart_window_secs;
3284 self
3285 }
3286
3287 #[must_use]
3289 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3290 self.drain_timeout_ms = drain_timeout_ms;
3291 self
3292 }
3293
3294 #[must_use]
3296 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3297 self.restart_backoff_ms = restart_backoff_ms;
3298 self
3299 }
3300
3301 #[must_use]
3303 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3304 self.restart_max_backoff_ms = restart_max_backoff_ms;
3305 self
3306 }
3307
3308 #[must_use]
3310 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3311 self.resources = resources;
3312 self
3313 }
3314
3315 #[must_use]
3317 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3318 self.tree = tree;
3319 self
3320 }
3321
3322 #[must_use]
3324 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3325 self.tree_unavailable = reason;
3326 self
3327 }
3328}
3329
3330#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3332pub struct ScriptModuleStatus {
3333 pub runtime: String,
3334 pub bun_version: Option<String>,
3335 pub path: PathBuf,
3336 pub sha256: Option<String>,
3337 pub size: Option<u64>,
3338 pub needs_review: bool,
3339}
3340
3341#[cfg(test)]
3342mod script_status_tests {
3343 use super::*;
3344
3345 #[test]
3346 fn script_status_roundtrips_and_old_supervisor_entries_remain_readable() {
3347 let old = SupervisorEntry::new(
3348 "example",
3349 "running",
3350 true,
3351 true,
3352 SupervisorHealthStatus::Unknown,
3353 );
3354 let value = serde_json::to_value(&old).unwrap();
3355 assert!(value.get("script").is_none());
3356 assert!(serde_json::from_value::<SupervisorEntry>(value)
3357 .unwrap()
3358 .script
3359 .is_none());
3360 let current = old.with_script(Some(ScriptModuleStatus {
3361 runtime: "bun".into(),
3362 bun_version: None,
3363 path: "bundle.js".into(),
3364 sha256: Some("ab".repeat(32)),
3365 size: Some(3),
3366 needs_review: true,
3367 }));
3368 let decoded: SupervisorEntry =
3369 serde_json::from_slice(&serde_json::to_vec(¤t).unwrap()).unwrap();
3370 assert_eq!(decoded, current);
3371 }
3372}
3373
3374#[derive(Debug, Clone, PartialEq)]
3377pub enum ChildResourceUsage {
3378 Measured(ChildResourceReading),
3379 Unavailable {
3380 reason: ChildResourceUnavailableReason,
3381 },
3382 Unknown {
3385 tag: String,
3386 body: OrderedJsonObject,
3387 },
3388}
3389
3390#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3393#[non_exhaustive]
3394pub struct ChildResourceReading {
3395 pub memory_bytes: u64,
3398 pub memory_kind: ChildMemoryKind,
3399 #[serde(default, skip_serializing_if = "Option::is_none")]
3402 pub swap_bytes: Option<u64>,
3403 pub cpu_user_ms: u64,
3407 pub cpu_system_ms: u64,
3410}
3411
3412impl ChildResourceReading {
3413 #[must_use]
3415 pub fn new(
3416 memory_bytes: u64,
3417 memory_kind: ChildMemoryKind,
3418 cpu_user_ms: u64,
3419 cpu_system_ms: u64,
3420 ) -> Self {
3421 Self {
3422 memory_bytes,
3423 memory_kind,
3424 cpu_user_ms,
3425 cpu_system_ms,
3426 swap_bytes: None,
3427 }
3428 }
3429
3430 #[must_use]
3432 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3433 self.swap_bytes = swap_bytes;
3434 self
3435 }
3436}
3437
3438open_string_enum! {
3439 ChildMemoryKind {
3441 PhysFootprint => "phys_footprint",
3445 ResidentSet => "resident_set",
3448 WindowsWorkingSet => "windows_working_set",
3451 }
3452}
3453
3454open_string_enum! {
3455 ChildResourceUnavailableReason {
3457 NotRunning => "not_running",
3459 UnsupportedPlatform => "unsupported_platform",
3461 Unreadable => "unreadable",
3464 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3467 }
3468}
3469
3470#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3471#[serde(rename_all = "snake_case")]
3472pub enum SupervisorHealthStatus {
3473 Ok,
3474 Degraded,
3475 Failing,
3476 Unresponsive,
3477 Unknown,
3478}
3479
3480#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3481pub struct SupervisorHealthEntry {
3482 pub module_id: String,
3483 pub status: SupervisorHealthStatus,
3484 #[serde(default, skip_serializing_if = "Option::is_none")]
3490 pub detail: Option<String>,
3491 #[serde(default, skip_serializing_if = "Option::is_none")]
3496 pub metrics: Option<serde_json::Value>,
3497 pub consecutive_failures: u32,
3498 #[serde(default)]
3501 pub late_answer_count: u64,
3502 #[serde(default, skip_serializing_if = "Option::is_none")]
3504 pub last_late_answer_latency_ms: Option<u64>,
3505 #[serde(default)]
3510 pub last_action: Option<String>,
3511 #[serde(default)]
3514 pub last_action_ms: Option<u64>,
3515 #[serde(default, skip_serializing_if = "Option::is_none")]
3528 pub last_probe_ms: Option<u64>,
3529}
3530
3531#[cfg(test)]
3532mod tests {
3533 #[test]
3534 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3535 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3536 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3537 assert_eq!(decoded.configured_enabled, None);
3538 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3539 }
3540
3541 #[test]
3542 fn configured_enabled_values_round_trip_in_list() {
3543 for enabled in [false, true] {
3544 let entry = SupervisorEntry::new(
3545 "provider",
3546 "running",
3547 true,
3548 true,
3549 SupervisorHealthStatus::Unknown,
3550 )
3551 .with_configured_enabled(Some(enabled));
3552 let entry_json = serde_json::to_value(&entry).unwrap();
3553 assert_eq!(entry_json["configured_enabled"], enabled);
3554 assert_eq!(
3555 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3556 entry
3557 );
3558 }
3559 }
3560
3561 #[test]
3562 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3563 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3564 volume_serial_number: u64::MAX,
3565 file_id: [
3566 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3567 ],
3568 };
3569 let agreement = super::RunningImageAgreement::Match { evidence };
3570 let encoded = serde_json::to_string(&agreement).unwrap();
3571 assert!(encoded.contains("windows_spawn_file_id"));
3572 assert_eq!(
3573 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3574 agreement
3575 );
3576 }
3577
3578 #[test]
3579 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3580 assert_eq!(
3581 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3582 device: 7,
3583 inode: 11
3584 })
3585 .unwrap(),
3586 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3587 );
3588 assert_eq!(
3589 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3590 digest: "abc".to_owned()
3591 })
3592 .unwrap(),
3593 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3594 );
3595 }
3596 use super::*;
3597 use subc_protocol::{BindIdentity, RouteTarget};
3598
3599 #[test]
3600 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3601 let entry = TerminalEntry {
3602 daemon_incarnation: Some("daemon-before-restart".into()),
3603 exit_code: Some(1),
3604 exit_signal: None,
3605 at_ms: 1_700_000_000_123,
3606 disposition: TerminalDisposition::Restarting,
3607 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3608 disposition_detail: None,
3609 };
3610 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3611 assert_eq!(
3612 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3613 ["exit_kind"],
3614 "deliberate_severance"
3615 );
3616
3617 #[derive(serde::Deserialize)]
3618 struct LegacyTerminalEntry {
3619 exit_code: Option<i32>,
3620 exit_signal: Option<i32>,
3621 at_ms: u64,
3622 disposition: TerminalDisposition,
3623 }
3624
3625 let decoded: LegacyTerminalEntry =
3626 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3627 assert_eq!(decoded.exit_code, Some(1));
3628 assert_eq!(decoded.exit_signal, None);
3629 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3630 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3631
3632 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3633 let future: TerminalEntry =
3634 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3635 assert_eq!(
3636 future.exit_kind,
3637 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3638 );
3639 }
3640
3641 #[test]
3642 fn terminal_incarnation_is_optional_for_older_daemons() {
3643 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3644 "at_ms": 123,
3645 "disposition": "stopped"
3646 }))
3647 .unwrap();
3648 let encoded = serde_json::to_value(&entry).unwrap();
3649 assert_eq!(
3650 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3651 (None, None)
3652 );
3653 }
3654
3655 #[test]
3656 fn route_poll_uses_kind_field() {
3657 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3658 route_channel: 7,
3659 route_epoch: 11,
3660 kind: PollKind::Status,
3661 })
3662 .unwrap();
3663
3664 assert_eq!(body["op"], "route.poll");
3665 assert_eq!(body["route_epoch"], 11);
3666 assert_eq!(body["kind"], "status");
3667 assert!(body.get("op").is_some());
3668 }
3669
3670 #[test]
3671 fn route_open_is_internally_tagged() {
3672 let request = ClientControlRequest::RouteOpen {
3673 busy_refusals: None,
3674 target: RouteTarget::ToolProvider {
3675 module_id: "aft".to_string(),
3676 },
3677 identity: BindIdentity::new("opencode", "session-1"),
3678 consumer_identity: None,
3679 consumer_capabilities: None,
3680 role_versions: None,
3681 admission_facts: None,
3682 scope: None,
3683 };
3684
3685 let body = serde_json::to_value(request).unwrap();
3686 assert_eq!(body["op"], "route.open");
3687 assert_eq!(body["target"]["kind"], "tool_provider");
3688 assert!(body.get("consumer_identity").is_none());
3689 assert!(body.get("consumer_capabilities").is_none());
3690 assert!(body.get("role_versions").is_none());
3691 }
3692
3693 #[test]
3694 fn route_open_without_optional_fields_still_decodes() {
3695 let body = serde_json::json!({
3696 "op": "route.open",
3697 "target": { "kind": "tool_provider", "module_id": "aft" },
3698 "identity": {
3699 "project_root": "/tmp/project",
3700 "harness": "opencode",
3701 "session": "session-1"
3702 }
3703 });
3704
3705 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3706 let ClientControlRequest::RouteOpen {
3707 consumer_identity,
3708 consumer_capabilities,
3709 role_versions,
3710 admission_facts,
3711 ..
3712 } = decoded
3713 else {
3714 panic!("decoded wrong request variant");
3715 };
3716 assert_eq!(consumer_identity, None);
3717 assert_eq!(consumer_capabilities, None);
3718 assert_eq!(role_versions, None);
3719 assert_eq!(admission_facts, None);
3720 }
3721
3722 #[test]
3723 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3724 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3725 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3726 match decoded {
3727 ClientControlPush::RouteClosed {
3728 excluded_subscriptions,
3729 terminal,
3730 ..
3731 } => {
3732 assert_eq!(excluded_subscriptions, 0);
3733 assert_eq!(terminal, None);
3734 }
3735 other => panic!("unexpected push: {other:?}"),
3736 }
3737 assert!(!serde_json::to_string(&decoded)
3738 .unwrap()
3739 .contains("terminal"));
3740 }
3741
3742 #[test]
3743 fn old_route_closed_decoder_ignores_new_terminal_field() {
3744 #[derive(serde::Deserialize)]
3745 #[serde(tag = "op")]
3746 enum LegacyClientControlPush {
3747 #[serde(rename = "route.closed")]
3748 RouteClosed {
3749 module_id: String,
3750 reason: RouteCloseReason,
3751 drained: bool,
3752 abandoned: u32,
3753 },
3754 }
3755
3756 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3757 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3758 match decoded {
3759 LegacyClientControlPush::RouteClosed {
3760 module_id,
3761 reason,
3762 drained,
3763 abandoned,
3764 } => {
3765 assert_eq!(module_id, "aft-tools");
3766 assert_eq!(reason, RouteCloseReason::Crash);
3767 assert!(!drained);
3768 assert_eq!(abandoned, 0);
3769 }
3770 }
3771 }
3772
3773 #[test]
3774 fn supervisor_routes_is_a_control_plane_request() {
3775 let body = serde_json::json!({
3776 "op": "supervisor.routes",
3777 "module_id": "aft"
3778 });
3779
3780 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3781 assert_eq!(serde_json::to_value(request).unwrap(), body);
3782 }
3783
3784 #[test]
3785 fn diagnostic_string_enums_retain_unknown_wire_values() {
3786 let reason: RunningImageUnavailableReason =
3787 serde_json::from_str("\"future_reason\"").unwrap();
3788 let disposition: TerminalDisposition =
3789 serde_json::from_str("\"future_disposition\"").unwrap();
3790
3791 assert_eq!(
3792 reason,
3793 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3794 );
3795 assert_eq!(
3796 disposition,
3797 TerminalDisposition::Unknown("future_disposition".to_string())
3798 );
3799 }
3800
3801 #[test]
3802 fn diagnostic_string_enums_preserve_existing_wire_names() {
3803 let names = [
3804 (RunningImageUnavailableReason::NotRunning, "not_running"),
3805 (
3806 RunningImageUnavailableReason::UnsupportedPlatform,
3807 "unsupported_platform",
3808 ),
3809 (
3810 RunningImageUnavailableReason::RunningExecutableUnreadable,
3811 "running_executable_unreadable",
3812 ),
3813 (
3814 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3815 "running_executable_permission_denied",
3816 ),
3817 (
3818 RunningImageUnavailableReason::ProcessHidden,
3819 "process_hidden",
3820 ),
3821 (
3822 RunningImageUnavailableReason::SpawnedPathUnreadable,
3823 "spawned_path_unreadable",
3824 ),
3825 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3826 (
3827 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3828 "process_identity_unconfirmed",
3829 ),
3830 ];
3831 for (value, expected) in names {
3832 let wire = serde_json::to_string(&value).unwrap();
3833 assert_eq!(wire, format!("\"{expected}\""));
3834 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3835 assert_eq!(decoded, value);
3836 }
3837
3838 for (value, expected) in [
3839 (TerminalDisposition::Stopped, "stopped"),
3840 (TerminalDisposition::Disabled, "disabled"),
3841 (TerminalDisposition::Failed, "failed"),
3842 (TerminalDisposition::Restarting, "restarting"),
3843 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3844 ] {
3845 let wire = serde_json::to_string(&value).unwrap();
3846 assert_eq!(wire, format!("\"{expected}\""));
3847 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3848 assert_eq!(decoded, value);
3849 }
3850 }
3851
3852 #[test]
3853 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3854 let entry = SupervisorEntry::new(
3855 "waiting-module",
3856 "starting",
3857 true,
3858 false,
3859 SupervisorHealthStatus::Unknown,
3860 );
3861 let old_wire = serde_json::to_value(&entry).unwrap();
3862 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3863 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3864 assert_eq!(decoded.waiting_for_previous_pid, None);
3865 let entry = entry.with_waiting_for_previous_pid(Some(42));
3866 let wire = serde_json::to_value(&entry).unwrap();
3867 assert_eq!(wire["waiting_for_previous_pid"], 42);
3868 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3869 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3870 }
3871
3872 #[test]
3873 fn diagnostic_string_enums_reject_non_string_bodies() {
3874 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3875 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3876 }
3877
3878 #[test]
3879 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3880 let body = serde_json::json!({
3881 "op": "supervisor.provenance",
3882 "daemon": {
3883 "daemon_build": {},
3884 "daemon_observed": {
3885 "running_image": {
3886 "status": "unavailable",
3887 "reason": "not_running"
3888 }
3889 }
3890 },
3891 "modules": [
3892 {
3893 "module_id": "future",
3894 "module_declared": { "status": "unverifiable" },
3895 "daemon_observed": {
3896 "running_image": {
3897 "status": "unavailable",
3898 "reason": "future_reason"
3899 }
3900 }
3901 },
3902 {
3903 "module_id": "healthy-a",
3904 "module_declared": { "status": "unverifiable" },
3905 "daemon_observed": {
3906 "running_image": {
3907 "status": "match",
3908 "evidence": {
3909 "method": "linux_proc_sha256",
3910 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3911 }
3912 }
3913 }
3914 },
3915 {
3916 "module_id": "healthy-b",
3917 "module_declared": { "status": "unverifiable" },
3918 "daemon_observed": {
3919 "running_image": {
3920 "status": "unavailable",
3921 "reason": "unsupported_platform"
3922 }
3923 }
3924 }
3925 ]
3926 });
3927
3928 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3929 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3930 panic!("decoded wrong response variant");
3931 };
3932 assert_eq!(modules.len(), 3);
3933 assert_eq!(modules[0].module_id, "future");
3934 assert_eq!(
3935 modules[0].daemon_observed.running_image,
3936 RunningImageAgreement::Unavailable {
3937 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3938 }
3939 );
3940 assert_eq!(modules[1].module_id, "healthy-a");
3941 assert_eq!(modules[2].module_id, "healthy-b");
3942 }
3943
3944 #[test]
3945 fn tagged_unknown_values_retain_tag_and_body() {
3946 macro_rules! assert_unknown_round_trip {
3947 ($ty:ident, $field:literal, $value:expr) => {
3948 let value = $value;
3949 let wire = serde_json::to_string(&value).unwrap();
3950 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3951 match decoded {
3952 $ty::Unknown { tag, body } => {
3953 assert_eq!(tag, value[$field].as_str().unwrap());
3954 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3955 }
3956 _ => panic!("decoded known variant"),
3957 }
3958 };
3959 }
3960
3961 assert_unknown_round_trip!(
3962 ModuleDeclaredProvenance,
3963 "status",
3964 serde_json::json!({"status": "future", "build": {"version": 7}})
3965 );
3966 assert_unknown_round_trip!(
3967 RunningImageAgreement,
3968 "status",
3969 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3970 );
3971 assert_unknown_round_trip!(
3972 RunningImageEvidence,
3973 "method",
3974 serde_json::json!({"method": "future", "digest": "abc"})
3975 );
3976 assert_unknown_round_trip!(
3977 SupervisorRouteConsumer,
3978 "kind",
3979 serde_json::json!({"kind": "future", "module_id": "m"})
3980 );
3981 assert_unknown_round_trip!(
3982 StderrCaptureState,
3983 "state",
3984 serde_json::json!({"state": "future", "reason": "because"})
3985 );
3986 assert_unknown_round_trip!(
3987 StderrTailEntry,
3988 "kind",
3989 serde_json::json!({"kind": "future", "text": "line"})
3990 );
3991 assert_unknown_round_trip!(
3992 ChildResourceUsage,
3993 "status",
3994 serde_json::json!({"status": "future", "memory_bytes": 1})
3995 );
3996 }
3997
3998 #[test]
3999 fn child_resource_usage_round_trips_both_known_states() {
4000 let measured = ChildResourceUsage::Measured(ChildResourceReading {
4001 memory_bytes: 0,
4002 memory_kind: ChildMemoryKind::ResidentSet,
4003 swap_bytes: Some(0),
4004 cpu_user_ms: 0,
4005 cpu_system_ms: 0,
4006 });
4007 let wire = serde_json::to_value(&measured).unwrap();
4008 assert_eq!(
4009 wire,
4010 serde_json::json!({
4011 "status": "measured",
4012 "memory_bytes": 0,
4013 "memory_kind": "resident_set",
4014 "swap_bytes": 0,
4015 "cpu_user_ms": 0,
4016 "cpu_system_ms": 0
4017 })
4018 );
4019 assert_eq!(
4020 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4021 measured
4022 );
4023
4024 let unavailable = ChildResourceUsage::Unavailable {
4025 reason: ChildResourceUnavailableReason::NotRunning,
4026 };
4027 let wire = serde_json::to_value(&unavailable).unwrap();
4028 assert_eq!(
4029 wire,
4030 serde_json::json!({"status": "unavailable", "reason": "not_running"})
4031 );
4032 assert_eq!(
4033 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4034 unavailable
4035 );
4036 }
4037
4038 #[test]
4039 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
4040 let stamped: StderrTailEntry = serde_json::from_str(
4044 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
4045 )
4046 .unwrap();
4047 assert_eq!(
4048 stamped,
4049 StderrTailEntry::Line {
4050 text: "boom".to_string(),
4051 truncated: true,
4052 at_ms: Some(1_789_801_440_685),
4053 }
4054 );
4055 let unstamped: StderrTailEntry =
4056 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
4057 assert_eq!(
4058 unstamped,
4059 StderrTailEntry::Line {
4060 text: "boom".to_string(),
4061 truncated: false,
4062 at_ms: None,
4063 }
4064 );
4065 assert_eq!(
4068 serde_json::to_string(&unstamped).unwrap(),
4069 r#"{"kind":"line","text":"boom"}"#
4070 );
4071 assert_eq!(
4072 serde_json::to_value(&stamped).unwrap()["at_ms"],
4073 serde_json::json!(1_789_801_440_685u64)
4074 );
4075 }
4076
4077 #[test]
4078 fn tagged_unknown_values_round_trip_the_original_json() {
4079 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
4080 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4081 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4082 }
4083
4084 #[test]
4085 fn tagged_unknown_values_round_trip_trailing_tag() {
4086 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
4087 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4088 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4089
4090 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
4091 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4092 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4093 }
4094
4095 #[test]
4096 fn tagged_unknown_values_round_trip_middle_tag() {
4097 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
4098 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4099 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4100
4101 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
4102 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4103 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4104 }
4105
4106 #[test]
4107 fn tagged_unknown_values_round_trip_deep_payload() {
4108 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
4109 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4110 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4111
4112 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
4113 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4114 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4115 }
4116
4117 #[test]
4118 fn tagged_unknown_values_reject_non_object_bodies() {
4119 for wire in ["42", r#""future""#, "[]"] {
4120 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
4121 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
4122 }
4123 }
4124
4125 #[test]
4126 fn duplicate_discriminators_reject_without_panicking() {
4127 assert_eq!(
4128 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
4129 .unwrap(),
4130 ModuleDeclaredProvenance::Unverifiable
4131 );
4132 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
4133 .unwrap()
4134 {
4135 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
4136 _ => panic!("future discriminator decoded as a known variant"),
4137 }
4138
4139 let wires = [
4140 r#"{"status":"reported","status":"unverifiable"}"#,
4141 r#"{"status":"unverifiable","status":"reported"}"#,
4142 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4143 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4144 ];
4145
4146 for wire in wires {
4147 let result =
4148 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4149 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4150 assert!(
4151 result.unwrap().is_err(),
4152 "duplicate discriminator decoded: {wire}"
4153 );
4154 }
4155
4156 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4157 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4158 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4159 assert!(
4160 result.unwrap().is_err(),
4161 "duplicate discriminator decoded: {wire}"
4162 );
4163 }
4164
4165 #[test]
4166 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4167 let known_wire =
4168 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4169 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4170 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4171
4172 for wire in [
4173 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4174 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4175 ] {
4176 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4177 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4178 }
4179
4180 for wire in [
4181 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4182 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4183 ] {
4184 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4185 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4186 }
4187
4188 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4189 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4190 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4191
4192 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4193 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4194 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4195 }
4196
4197 #[test]
4198 fn tagged_unknown_member_does_not_discard_known_siblings() {
4199 let body = serde_json::json!({
4200 "modules": [{
4201 "module_id": "target",
4202 "routes": [
4203 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4204 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4205 ]
4206 }]
4207 });
4208 let decoded: ClientControlResponse = serde_json::from_value(
4209 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4210 )
4211 .unwrap();
4212 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4213 panic!("decoded wrong response variant");
4214 };
4215 assert_eq!(modules[0].routes.len(), 2);
4216 assert_eq!(
4217 modules[0].routes[1].consumer,
4218 SupervisorRouteConsumer::Direct { connection_id: 7 }
4219 );
4220 }
4221}
4222
4223#[cfg(test)]
4224mod launch_nonce_redaction_tests {
4225 use super::*;
4226
4227 const NONCE: &str = "nonce-f00dfeed1234abcd";
4228
4229 fn identity() -> ConsumerIdentity {
4230 ConsumerIdentity {
4231 module_id: "wernicke".to_string(),
4232 launch_nonce: NONCE.to_string(),
4233 }
4234 }
4235
4236 #[test]
4237 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4238 let printed = format!("{:?}", identity());
4239 assert!(printed.contains("wernicke"), "{printed}");
4240 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4241 }
4242
4243 #[test]
4244 fn route_open_request_debug_never_prints_the_nonce() {
4245 let request = ClientControlRequest::RouteOpen {
4246 busy_refusals: None,
4247 target: subc_protocol::RouteTarget::ToolProvider {
4248 module_id: "broca".to_string(),
4249 },
4250 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4251 consumer_identity: Some(identity()),
4252 consumer_capabilities: None,
4253 role_versions: None,
4254 admission_facts: None,
4255 scope: None,
4256 };
4257 let printed = format!("{request:?}");
4258 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4259 }
4260}
4261
4262#[cfg(test)]
4263mod reader_skew_tests {
4264 use super::*;
4265 use serde_json::{json, Value};
4266
4267 fn catalog() -> Value {
4268 json!({"module_id": "provider", "roles": [], "control_ops": []})
4269 }
4270
4271 fn reply() -> Value {
4272 json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4273 }
4274
4275 fn target() -> Value {
4276 json!({
4277 "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4278 "authority_epoch": 23, "first_party": true,
4279 "approved_declarations_digest": "approved"
4280 })
4281 }
4282
4283 fn request() -> Value {
4284 json!({
4285 "op": "route.open",
4286 "target": {"kind": "tool_provider", "module_id": "provider"},
4287 "identity": {"harness": "test", "session": "session-1"}
4288 })
4289 }
4290
4291 #[test]
4292 fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4293 let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4294 let built = CatalogEntry::new("provider", vec![], vec![]);
4295 assert_eq!(old, built);
4296 assert_eq!(old.first_party, None);
4297 let old_bytes = serde_json::to_value(&old).unwrap();
4298 let additions = json!({
4299 "incarnation": "daemon", "spawn": 17, "first_party": false,
4300 "origin": "development", "requested_declarations_digest": "requested",
4301 "approved_declarations_digest": "approved"
4302 });
4303 let mut body = catalog();
4304 for (key, value) in additions.as_object().unwrap() {
4305 assert!(old_bytes.get(key).is_none(), "{key}");
4306 body[key] = value.clone();
4307 }
4308 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4309 let encoded = serde_json::to_value(&decoded).unwrap();
4310 for (key, value) in additions.as_object().unwrap() {
4311 assert_eq!(&encoded[key], value, "{key}");
4312 }
4313 assert_eq!(decoded.first_party, Some(false));
4314 assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4315 }
4316
4317 #[test]
4318 fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4319 let mut body = catalog();
4320 body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4321 body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4322 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4323 let encoded = serde_json::to_value(decoded).unwrap();
4324 for key in ["requested_declarations", "approved_declarations"] {
4325 assert_eq!(encoded[key], body[key]);
4326 }
4327 let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4328 assert_eq!(unfiltered.approved_declarations, None);
4329 assert_eq!(unfiltered.requested_declarations, None);
4330 }
4331
4332 #[test]
4333 fn reader_skew_catalog_unknown_origin_is_other() {
4334 let mut body = catalog();
4335 body["origin"] = json!("future-origin");
4336 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4337 assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4338 }
4339
4340 #[test]
4341 fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4342 let mut body = catalog();
4343 body["spawn"] = json!(9_007_199_254_740_991_u64);
4344 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4345 assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4346 for invalid in [
4347 json!(9_007_199_254_740_992_u64),
4348 json!(-1),
4349 json!(1.5),
4350 json!("17"),
4351 ] {
4352 body["spawn"] = invalid;
4353 assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4354 }
4355 }
4356
4357 #[test]
4358 fn reader_skew_catalog_watch_request_uses_subscription_op() {
4359 let body = json!({"op": "catalog.watch"});
4360 let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4361 assert_eq!(request, CatalogWatchRequest::new());
4362 assert_eq!(serde_json::to_value(request).unwrap(), body);
4363 assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4364 for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4365 assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4366 }
4367 }
4368
4369 #[test]
4370 fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4371 for generation in [0, 19, 42] {
4372 let body = json!({"op": "catalog.watch", "generation": generation});
4373 let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4374 assert_eq!(push, CatalogWatchResponse::new(generation));
4375 assert_eq!(serde_json::to_value(push).unwrap(), body);
4376 }
4377 assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4378 for invalid in [
4379 json!({"op": "catalog.watch"}),
4380 json!({"op": "activity.subscribe", "generation": 1}),
4381 ] {
4382 assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4383 }
4384 }
4385
4386 #[test]
4387 fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4388 let mut body = reply();
4389 let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4390 let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4391 assert_eq!(empty, RouteOpenReplyExt::new());
4392 empty.write_to(&mut body).unwrap();
4393 assert_eq!(body, reply());
4394 body["target"] = target();
4395 let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4396 assert_eq!(
4397 decoded.target.as_ref().unwrap().kind,
4398 RouteOpenTargetKind::Spawn
4399 );
4400 let mut encoded = reply();
4401 RouteOpenReplyExt::new()
4402 .with_target(decoded.target)
4403 .write_to(&mut encoded)
4404 .unwrap();
4405 assert_eq!(encoded, body);
4406 assert_eq!(
4407 serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4408 legacy
4409 );
4410 RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4411 assert_eq!(encoded, reply());
4412 }
4413
4414 #[test]
4415 fn reader_skew_route_open_incomplete_target_is_unmarked() {
4416 let mut body = reply();
4417 body["target"] = target();
4418 assert!(RouteOpenReplyExt::read_from(&body)
4419 .unwrap()
4420 .target
4421 .is_some());
4422 for key in [
4423 "incarnation",
4424 "kind",
4425 "spawn",
4426 "authority_epoch",
4427 "first_party",
4428 "approved_declarations_digest",
4429 ] {
4430 let mut incomplete = body.clone();
4431 incomplete["target"].as_object_mut().unwrap().remove(key);
4432 assert_eq!(
4433 RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4434 None,
4435 "{key}"
4436 );
4437 }
4438 body["target"] = Value::Null;
4439 assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4440 }
4441
4442 #[test]
4443 fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4444 for (kind, expected) in [
4445 ("prefix", RouteOpenTargetKind::Prefix),
4446 ("unsupervised", RouteOpenTargetKind::Unsupervised),
4447 ] {
4448 let mut body = reply();
4449 body["target"] = target();
4450 body["target"]["kind"] = json!(kind);
4451 body["target"]["spawn"] = json!("not-a-spawn");
4453 body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4454 body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4455 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4456 let target = ext.target.as_ref().unwrap();
4457 assert_eq!(target.kind, expected);
4458 assert_eq!(target.spawn, None);
4459 assert_eq!(target.authority_epoch, None);
4460 assert_eq!(target.approved_declarations_digest, None);
4461 assert!(!target.first_party);
4462 let mut encoded = reply();
4463 ext.write_to(&mut encoded).unwrap();
4464 for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
4465 assert!(encoded["target"].get(key).is_none());
4466 }
4467 }
4468 }
4469
4470 #[test]
4471 fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4472 let mut body = reply();
4473 body["target"] = target();
4474 body["target"]["kind"] = json!("future-kind");
4475 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4476 let target = ext.target.unwrap();
4477 assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4478 assert_eq!(target.spawn, None);
4479 assert_eq!(target.authority_epoch, None);
4480 assert_eq!(target.approved_declarations_digest, None);
4481 assert!(!target.first_party);
4482 }
4483
4484 #[test]
4485 fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4486 for field in ["spawn", "authority_epoch"] {
4487 let mut body = reply();
4488 body["target"] = target();
4489 body["target"][field] = json!(9_007_199_254_740_991_u64);
4490 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4491 assert_eq!(
4492 serde_json::to_value(ext).unwrap()["target"][field],
4493 9_007_199_254_740_991_u64
4494 );
4495 for invalid in [
4496 json!(9_007_199_254_740_992_u64),
4497 json!(-1),
4498 json!(1.5),
4499 json!("17"),
4500 ] {
4501 body["target"][field] = invalid;
4502 assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4503 let mut incomplete = body.clone();
4504 incomplete["target"]
4505 .as_object_mut()
4506 .unwrap()
4507 .remove("incarnation");
4508 assert!(
4509 RouteOpenReplyExt::read_from(&incomplete).is_err(),
4510 "{field}"
4511 );
4512 }
4513 }
4514 }
4515
4516 #[test]
4517 fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4518 let mut body = request();
4519 let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4520 assert_eq!(
4521 RouteOpenRequestExt::read_from(&body).unwrap(),
4522 RouteOpenRequestExt::new()
4523 );
4524 RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4525 assert_eq!(body, request());
4526 body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4527 let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4528 assert_eq!(
4529 decoded.accepts_close_reasons,
4530 Some(vec!["authority_changed".into(), "future-reason".into()])
4531 );
4532 let mut encoded = request();
4533 RouteOpenRequestExt::new()
4534 .with_accepts_close_reasons(decoded.accepts_close_reasons)
4535 .write_to(&mut encoded)
4536 .unwrap();
4537 assert_eq!(encoded, body);
4538 assert_eq!(
4539 serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4540 legacy
4541 );
4542 RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4543 assert_eq!(encoded, request());
4544 assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4545 }
4546
4547 #[test]
4548 fn reader_skew_route_open_helpers_refuse_other_bodies() {
4549 for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4550 assert!(RouteOpenRequestExt::read_from(&body).is_err());
4551 assert!(RouteOpenReplyExt::read_from(&body).is_err());
4552 assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4553 assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4554 }
4555 }
4556
4557 #[test]
4558 fn reader_skew_route_open_target_constructor_validates_like_reader() {
4559 let spawn = RouteOpenTarget::new(
4560 "daemon",
4561 RouteOpenTargetKind::Spawn,
4562 Some(17),
4563 Some(23),
4564 true,
4565 Some("approved".into()),
4566 )
4567 .unwrap();
4568 assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4569 for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4570 assert!(RouteOpenTarget::new(
4571 "daemon",
4572 RouteOpenTargetKind::Spawn,
4573 Some(spawn),
4574 Some(epoch),
4575 true,
4576 Some("approved".into())
4577 )
4578 .is_err());
4579 }
4580 }
4581}
4582
4583#[cfg(test)]
4584mod claim_wire_tests {
4585 use super::*;
4586 use serde_json::{json, Value};
4587
4588 fn legacy_provenance() -> SupervisorModuleProvenance {
4589 SupervisorModuleProvenance {
4590 module_id: "worker".into(),
4591 module_declared: ModuleDeclaredProvenance::Unverifiable,
4592 daemon_observed: SupervisorObservedProcess {
4593 launch_nonce_source: None,
4594 pid: None,
4595 spawned_at_ms: None,
4596 spawned_from: None,
4597 running_image: RunningImageAgreement::Unavailable {
4598 reason: RunningImageUnavailableReason::NotRunning,
4599 },
4600 },
4601 }
4602 }
4603
4604 #[test]
4605 fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4606 let legacy = legacy_provenance();
4607 let original = serde_json::to_value(&legacy).unwrap();
4608 let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4609 assert_eq!(absent.registration, None);
4610 let mut wire = original.clone();
4611 absent.write_to(&mut wire).unwrap();
4612 assert_eq!(wire, original);
4613 for (method, spelling) in [
4614 (RegistrationMethod::Channel, "channel"),
4615 (RegistrationMethod::Nonce, "nonce"),
4616 ] {
4617 let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4618 ext.write_to(&mut wire).unwrap();
4619 assert_eq!(wire["registration"], spelling);
4620 assert_eq!(
4621 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4622 ext
4623 );
4624 let old_reader: SupervisorModuleProvenance =
4625 serde_json::from_value(wire.clone()).unwrap();
4626 assert_eq!(old_reader, legacy);
4627 assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4628 }
4629 absent.write_to(&mut wire).unwrap();
4630 assert_eq!(wire, original);
4631 for mut invalid in [Value::Null, json!([]), json!("entry")] {
4632 assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4633 assert!(absent.write_to(&mut invalid).is_err());
4634 }
4635 }
4636
4637 #[test]
4638 fn provenance_unknown_registration_is_not_channel_or_nonce() {
4639 let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4640 wire["registration"] = json!("future_method");
4641 let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4642 assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4643 assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4644 assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4645 wire["registration"] = json!(false);
4646 assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4647 }
4648
4649 #[test]
4650 fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4651 let original = serde_json::to_value(legacy_provenance()).unwrap();
4652 for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4653 let mut golden = original.clone();
4654 golden["registration_declaration"] = json!(declaration);
4655 let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4656 assert_eq!(
4657 serde_json::to_value(&extension).unwrap(),
4658 json!({
4659 "registration_declaration": declaration
4660 })
4661 );
4662 let mut written = original.clone();
4663 extension.write_to(&mut written).unwrap();
4664 assert_eq!(written, golden);
4665 assert_eq!(
4666 serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4667 legacy_provenance()
4668 );
4669 SupervisorModuleProvenanceExt::new()
4670 .write_to(&mut written)
4671 .unwrap();
4672 assert_eq!(written, original);
4673 }
4674 }
4675
4676 #[test]
4677 fn admission_refusal_is_optional_and_open() {
4678 let entry = SupervisorEntry::new(
4679 "worker",
4680 "stopped",
4681 true,
4682 false,
4683 SupervisorHealthStatus::Unknown,
4684 );
4685 let original = serde_json::to_value(&entry).unwrap();
4686 assert!(original.get("admission_refused").is_none());
4687 let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
4688 assert_eq!(read.admission_refused, None);
4689 assert_eq!(serde_json::to_value(read).unwrap(), original);
4690 assert_eq!(
4691 REGISTRATION_CHANNEL_UNSUPPORTED,
4692 "registration_channel_unsupported"
4693 );
4694 for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
4695 let mut wire = original.clone();
4696 wire["admission_refused"] = json!(reason);
4697 let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
4698 assert_eq!(read.admission_refused.as_deref(), Some(reason));
4699 assert_eq!(serde_json::to_value(read).unwrap(), wire);
4700 let built = entry.clone().with_admission_refused(Some(reason.into()));
4701 assert_eq!(serde_json::to_value(built).unwrap(), wire);
4702 }
4703 }
4704}