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")]
2956 pub accepting_drain: Option<bool>,
2957 #[serde(default, skip_serializing_if = "Option::is_none")]
2961 pub admission_refused: Option<String>,
2962 #[serde(default, skip_serializing_if = "Option::is_none")]
2966 pub next_retry_at_ms: Option<u64>,
2967 pub enabled: bool,
2968 #[serde(default, skip_serializing_if = "Option::is_none")]
2971 pub configured_enabled: Option<bool>,
2972 pub live: bool,
2982 #[serde(default)]
2986 pub protocol: ModuleProtocol,
2987 #[serde(default, skip_serializing_if = "Option::is_none")]
2990 pub launch_nonce_env: Option<bool>,
2991 #[serde(default, skip_serializing_if = "Option::is_none")]
2997 pub launch_nonce_source: Option<String>,
2998 pub health: SupervisorHealthStatus,
2999 #[serde(default, skip_serializing_if = "Option::is_none")]
3002 pub pending_reload: Option<PendingReloadVerdict>,
3003 #[serde(default)]
3009 pub last_probe_ms: Option<u64>,
3010 #[serde(default, skip_serializing_if = "Option::is_none")]
3014 pub last_exit_code: Option<i32>,
3015 #[serde(default, skip_serializing_if = "Option::is_none")]
3019 pub last_exit_signal: Option<i32>,
3020 #[serde(default, skip_serializing_if = "Option::is_none")]
3024 pub last_exit_ms: Option<u64>,
3025 #[serde(default, skip_serializing_if = "Option::is_none")]
3028 pub last_exit_kind: Option<TerminalExitKind>,
3029 #[serde(default, skip_serializing_if = "Option::is_none")]
3046 pub restart_count: Option<u32>,
3047 #[serde(default, skip_serializing_if = "Option::is_none")]
3050 pub max_restarts: Option<u32>,
3051 #[serde(default, skip_serializing_if = "Option::is_none")]
3054 pub lifetime_restarts: Option<u32>,
3055 #[serde(default, skip_serializing_if = "Option::is_none")]
3059 pub spawn_generation: Option<u64>,
3060 #[serde(default, skip_serializing_if = "Option::is_none")]
3070 pub restart_window_secs: Option<u64>,
3071 #[serde(default, skip_serializing_if = "Option::is_none")]
3075 pub drain_timeout_ms: Option<u64>,
3076 #[serde(default, skip_serializing_if = "Option::is_none")]
3079 pub restart_backoff_ms: Option<u64>,
3080 #[serde(default, skip_serializing_if = "Option::is_none")]
3083 pub restart_max_backoff_ms: Option<u64>,
3084 #[serde(default, skip_serializing_if = "Option::is_none")]
3097 pub resources: Option<ChildResourceUsage>,
3098 #[serde(default, skip_serializing_if = "Option::is_none")]
3100 pub tree: Option<TreeReading>,
3101 #[serde(default, skip_serializing_if = "Option::is_none")]
3107 pub tree_unavailable: Option<String>,
3108 #[serde(default, skip_serializing_if = "Option::is_none")]
3110 pub cpu_last_hour: Option<CpuLastHour>,
3111 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3113 pub pending: Vec<SupervisorPendingField>,
3114}
3115
3116impl SupervisorEntry {
3117 #[must_use]
3118 pub fn with_script(mut self, script: Option<ScriptModuleStatus>) -> Self {
3119 self.script = script;
3120 self
3121 }
3122 #[must_use]
3124 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3125 self.next_retry_at_ms = next_retry_at_ms;
3126 self
3127 }
3128
3129 #[must_use]
3131 pub fn new(
3132 module_id: impl Into<String>,
3133 state: impl Into<String>,
3134 enabled: bool,
3135 live: bool,
3136 health: SupervisorHealthStatus,
3137 ) -> Self {
3138 Self {
3139 module_id: module_id.into(),
3140 script: None,
3141 state: state.into(),
3142 admission_refused: None,
3143 next_retry_at_ms: None,
3144 waiting_for_previous_pid: None,
3145 accepting_drain: None,
3146 enabled,
3147 configured_enabled: None,
3148 live,
3149 protocol: ModuleProtocol::default(),
3150 launch_nonce_env: None,
3151 launch_nonce_source: None,
3152 health,
3153 pending_reload: None,
3154 last_probe_ms: None,
3155 last_exit_code: None,
3156 last_exit_signal: None,
3157 last_exit_ms: None,
3158 last_exit_kind: None,
3159 restart_count: None,
3160 max_restarts: None,
3161 lifetime_restarts: None,
3162 spawn_generation: None,
3163 restart_window_secs: None,
3164 drain_timeout_ms: None,
3165 restart_backoff_ms: None,
3166 restart_max_backoff_ms: None,
3167 resources: None,
3168 tree: None,
3169 tree_unavailable: None,
3170 cpu_last_hour: None,
3171 pending: Vec::new(),
3172 }
3173 }
3174
3175 #[must_use]
3177 pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3178 self.admission_refused = reason;
3179 self
3180 }
3181
3182 #[must_use]
3184 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3185 self.protocol = protocol;
3186 self
3187 }
3188
3189 #[must_use]
3191 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3192 self.configured_enabled = configured_enabled;
3193 self
3194 }
3195
3196 #[must_use]
3198 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3199 self.launch_nonce_env = launch_nonce_env;
3200 self
3201 }
3202
3203 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3204 self.launch_nonce_source = source;
3205 self
3206 }
3207
3208 #[must_use]
3209 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3210 self.waiting_for_previous_pid = pid;
3211 self
3212 }
3213
3214 #[must_use]
3216 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3217 self.pending_reload = pending_reload;
3218 self
3219 }
3220
3221 #[must_use]
3223 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3224 self.last_probe_ms = last_probe_ms;
3225 self
3226 }
3227
3228 #[must_use]
3230 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3231 self.last_exit_code = last_exit_code;
3232 self
3233 }
3234
3235 #[must_use]
3237 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3238 self.last_exit_signal = last_exit_signal;
3239 self
3240 }
3241
3242 #[must_use]
3244 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3245 self.last_exit_ms = last_exit_ms;
3246 self
3247 }
3248
3249 #[must_use]
3251 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3252 self.last_exit_kind = last_exit_kind;
3253 self
3254 }
3255
3256 #[must_use]
3258 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3259 self.restart_count = restart_count;
3260 self
3261 }
3262
3263 #[must_use]
3265 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3266 self.max_restarts = max_restarts;
3267 self
3268 }
3269
3270 #[must_use]
3272 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3273 self.lifetime_restarts = lifetime_restarts;
3274 self
3275 }
3276
3277 #[must_use]
3279 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3280 self.spawn_generation = spawn_generation;
3281 self
3282 }
3283
3284 #[must_use]
3286 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3287 self.restart_window_secs = restart_window_secs;
3288 self
3289 }
3290
3291 #[must_use]
3293 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3294 self.drain_timeout_ms = drain_timeout_ms;
3295 self
3296 }
3297
3298 #[must_use]
3300 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3301 self.restart_backoff_ms = restart_backoff_ms;
3302 self
3303 }
3304
3305 #[must_use]
3307 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3308 self.restart_max_backoff_ms = restart_max_backoff_ms;
3309 self
3310 }
3311
3312 #[must_use]
3314 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3315 self.resources = resources;
3316 self
3317 }
3318
3319 #[must_use]
3321 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3322 self.tree = tree;
3323 self
3324 }
3325
3326 #[must_use]
3328 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3329 self.tree_unavailable = reason;
3330 self
3331 }
3332}
3333
3334#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3336pub struct ScriptModuleStatus {
3337 pub runtime: String,
3338 pub bun_version: Option<String>,
3339 pub path: PathBuf,
3340 pub sha256: Option<String>,
3341 pub size: Option<u64>,
3342 pub needs_review: bool,
3343}
3344
3345#[cfg(test)]
3346mod script_status_tests {
3347 use super::*;
3348
3349 #[test]
3350 fn script_status_roundtrips_and_old_supervisor_entries_remain_readable() {
3351 let old = SupervisorEntry::new(
3352 "example",
3353 "running",
3354 true,
3355 true,
3356 SupervisorHealthStatus::Unknown,
3357 );
3358 let value = serde_json::to_value(&old).unwrap();
3359 assert!(value.get("script").is_none());
3360 assert!(serde_json::from_value::<SupervisorEntry>(value)
3361 .unwrap()
3362 .script
3363 .is_none());
3364 let current = old.with_script(Some(ScriptModuleStatus {
3365 runtime: "bun".into(),
3366 bun_version: None,
3367 path: "bundle.js".into(),
3368 sha256: Some("ab".repeat(32)),
3369 size: Some(3),
3370 needs_review: true,
3371 }));
3372 let decoded: SupervisorEntry =
3373 serde_json::from_slice(&serde_json::to_vec(¤t).unwrap()).unwrap();
3374 assert_eq!(decoded, current);
3375 }
3376}
3377
3378#[derive(Debug, Clone, PartialEq)]
3381pub enum ChildResourceUsage {
3382 Measured(ChildResourceReading),
3383 Unavailable {
3384 reason: ChildResourceUnavailableReason,
3385 },
3386 Unknown {
3389 tag: String,
3390 body: OrderedJsonObject,
3391 },
3392}
3393
3394#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3397#[non_exhaustive]
3398pub struct ChildResourceReading {
3399 pub memory_bytes: u64,
3402 pub memory_kind: ChildMemoryKind,
3403 #[serde(default, skip_serializing_if = "Option::is_none")]
3406 pub swap_bytes: Option<u64>,
3407 pub cpu_user_ms: u64,
3411 pub cpu_system_ms: u64,
3414}
3415
3416impl ChildResourceReading {
3417 #[must_use]
3419 pub fn new(
3420 memory_bytes: u64,
3421 memory_kind: ChildMemoryKind,
3422 cpu_user_ms: u64,
3423 cpu_system_ms: u64,
3424 ) -> Self {
3425 Self {
3426 memory_bytes,
3427 memory_kind,
3428 cpu_user_ms,
3429 cpu_system_ms,
3430 swap_bytes: None,
3431 }
3432 }
3433
3434 #[must_use]
3436 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3437 self.swap_bytes = swap_bytes;
3438 self
3439 }
3440}
3441
3442open_string_enum! {
3443 ChildMemoryKind {
3445 PhysFootprint => "phys_footprint",
3449 ResidentSet => "resident_set",
3452 WindowsWorkingSet => "windows_working_set",
3455 }
3456}
3457
3458open_string_enum! {
3459 ChildResourceUnavailableReason {
3461 NotRunning => "not_running",
3463 UnsupportedPlatform => "unsupported_platform",
3465 Unreadable => "unreadable",
3468 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3471 }
3472}
3473
3474#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3475#[serde(rename_all = "snake_case")]
3476pub enum SupervisorHealthStatus {
3477 Ok,
3478 Degraded,
3479 Failing,
3480 Unresponsive,
3481 Unknown,
3482}
3483
3484#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3485pub struct SupervisorHealthEntry {
3486 pub module_id: String,
3487 pub status: SupervisorHealthStatus,
3488 #[serde(default, skip_serializing_if = "Option::is_none")]
3494 pub detail: Option<String>,
3495 #[serde(default, skip_serializing_if = "Option::is_none")]
3500 pub metrics: Option<serde_json::Value>,
3501 pub consecutive_failures: u32,
3502 #[serde(default)]
3505 pub late_answer_count: u64,
3506 #[serde(default, skip_serializing_if = "Option::is_none")]
3508 pub last_late_answer_latency_ms: Option<u64>,
3509 #[serde(default)]
3514 pub last_action: Option<String>,
3515 #[serde(default)]
3518 pub last_action_ms: Option<u64>,
3519 #[serde(default, skip_serializing_if = "Option::is_none")]
3532 pub last_probe_ms: Option<u64>,
3533}
3534
3535#[cfg(test)]
3536mod tests {
3537 #[test]
3538 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3539 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3540 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3541 assert_eq!(decoded.configured_enabled, None);
3542 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3543 }
3544
3545 #[test]
3546 fn configured_enabled_values_round_trip_in_list() {
3547 for enabled in [false, true] {
3548 let entry = SupervisorEntry::new(
3549 "provider",
3550 "running",
3551 true,
3552 true,
3553 SupervisorHealthStatus::Unknown,
3554 )
3555 .with_configured_enabled(Some(enabled));
3556 let entry_json = serde_json::to_value(&entry).unwrap();
3557 assert_eq!(entry_json["configured_enabled"], enabled);
3558 assert_eq!(
3559 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3560 entry
3561 );
3562 }
3563 }
3564
3565 #[test]
3566 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3567 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3568 volume_serial_number: u64::MAX,
3569 file_id: [
3570 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3571 ],
3572 };
3573 let agreement = super::RunningImageAgreement::Match { evidence };
3574 let encoded = serde_json::to_string(&agreement).unwrap();
3575 assert!(encoded.contains("windows_spawn_file_id"));
3576 assert_eq!(
3577 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3578 agreement
3579 );
3580 }
3581
3582 #[test]
3583 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3584 assert_eq!(
3585 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3586 device: 7,
3587 inode: 11
3588 })
3589 .unwrap(),
3590 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3591 );
3592 assert_eq!(
3593 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3594 digest: "abc".to_owned()
3595 })
3596 .unwrap(),
3597 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3598 );
3599 }
3600 use super::*;
3601 use subc_protocol::{BindIdentity, RouteTarget};
3602
3603 #[test]
3604 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3605 let entry = TerminalEntry {
3606 daemon_incarnation: Some("daemon-before-restart".into()),
3607 exit_code: Some(1),
3608 exit_signal: None,
3609 at_ms: 1_700_000_000_123,
3610 disposition: TerminalDisposition::Restarting,
3611 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3612 disposition_detail: None,
3613 };
3614 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3615 assert_eq!(
3616 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3617 ["exit_kind"],
3618 "deliberate_severance"
3619 );
3620
3621 #[derive(serde::Deserialize)]
3622 struct LegacyTerminalEntry {
3623 exit_code: Option<i32>,
3624 exit_signal: Option<i32>,
3625 at_ms: u64,
3626 disposition: TerminalDisposition,
3627 }
3628
3629 let decoded: LegacyTerminalEntry =
3630 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3631 assert_eq!(decoded.exit_code, Some(1));
3632 assert_eq!(decoded.exit_signal, None);
3633 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3634 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3635
3636 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3637 let future: TerminalEntry =
3638 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3639 assert_eq!(
3640 future.exit_kind,
3641 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3642 );
3643 }
3644
3645 #[test]
3646 fn terminal_incarnation_is_optional_for_older_daemons() {
3647 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3648 "at_ms": 123,
3649 "disposition": "stopped"
3650 }))
3651 .unwrap();
3652 let encoded = serde_json::to_value(&entry).unwrap();
3653 assert_eq!(
3654 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3655 (None, None)
3656 );
3657 }
3658
3659 #[test]
3660 fn route_poll_uses_kind_field() {
3661 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3662 route_channel: 7,
3663 route_epoch: 11,
3664 kind: PollKind::Status,
3665 })
3666 .unwrap();
3667
3668 assert_eq!(body["op"], "route.poll");
3669 assert_eq!(body["route_epoch"], 11);
3670 assert_eq!(body["kind"], "status");
3671 assert!(body.get("op").is_some());
3672 }
3673
3674 #[test]
3675 fn route_open_is_internally_tagged() {
3676 let request = ClientControlRequest::RouteOpen {
3677 busy_refusals: None,
3678 target: RouteTarget::ToolProvider {
3679 module_id: "aft".to_string(),
3680 },
3681 identity: BindIdentity::new("opencode", "session-1"),
3682 consumer_identity: None,
3683 consumer_capabilities: None,
3684 role_versions: None,
3685 admission_facts: None,
3686 scope: None,
3687 };
3688
3689 let body = serde_json::to_value(request).unwrap();
3690 assert_eq!(body["op"], "route.open");
3691 assert_eq!(body["target"]["kind"], "tool_provider");
3692 assert!(body.get("consumer_identity").is_none());
3693 assert!(body.get("consumer_capabilities").is_none());
3694 assert!(body.get("role_versions").is_none());
3695 }
3696
3697 #[test]
3698 fn route_open_without_optional_fields_still_decodes() {
3699 let body = serde_json::json!({
3700 "op": "route.open",
3701 "target": { "kind": "tool_provider", "module_id": "aft" },
3702 "identity": {
3703 "project_root": "/tmp/project",
3704 "harness": "opencode",
3705 "session": "session-1"
3706 }
3707 });
3708
3709 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3710 let ClientControlRequest::RouteOpen {
3711 consumer_identity,
3712 consumer_capabilities,
3713 role_versions,
3714 admission_facts,
3715 ..
3716 } = decoded
3717 else {
3718 panic!("decoded wrong request variant");
3719 };
3720 assert_eq!(consumer_identity, None);
3721 assert_eq!(consumer_capabilities, None);
3722 assert_eq!(role_versions, None);
3723 assert_eq!(admission_facts, None);
3724 }
3725
3726 #[test]
3727 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3728 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3729 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3730 match decoded {
3731 ClientControlPush::RouteClosed {
3732 excluded_subscriptions,
3733 terminal,
3734 ..
3735 } => {
3736 assert_eq!(excluded_subscriptions, 0);
3737 assert_eq!(terminal, None);
3738 }
3739 other => panic!("unexpected push: {other:?}"),
3740 }
3741 assert!(!serde_json::to_string(&decoded)
3742 .unwrap()
3743 .contains("terminal"));
3744 }
3745
3746 #[test]
3747 fn old_route_closed_decoder_ignores_new_terminal_field() {
3748 #[derive(serde::Deserialize)]
3749 #[serde(tag = "op")]
3750 enum LegacyClientControlPush {
3751 #[serde(rename = "route.closed")]
3752 RouteClosed {
3753 module_id: String,
3754 reason: RouteCloseReason,
3755 drained: bool,
3756 abandoned: u32,
3757 },
3758 }
3759
3760 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3761 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3762 match decoded {
3763 LegacyClientControlPush::RouteClosed {
3764 module_id,
3765 reason,
3766 drained,
3767 abandoned,
3768 } => {
3769 assert_eq!(module_id, "aft-tools");
3770 assert_eq!(reason, RouteCloseReason::Crash);
3771 assert!(!drained);
3772 assert_eq!(abandoned, 0);
3773 }
3774 }
3775 }
3776
3777 #[test]
3778 fn supervisor_routes_is_a_control_plane_request() {
3779 let body = serde_json::json!({
3780 "op": "supervisor.routes",
3781 "module_id": "aft"
3782 });
3783
3784 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3785 assert_eq!(serde_json::to_value(request).unwrap(), body);
3786 }
3787
3788 #[test]
3789 fn diagnostic_string_enums_retain_unknown_wire_values() {
3790 let reason: RunningImageUnavailableReason =
3791 serde_json::from_str("\"future_reason\"").unwrap();
3792 let disposition: TerminalDisposition =
3793 serde_json::from_str("\"future_disposition\"").unwrap();
3794
3795 assert_eq!(
3796 reason,
3797 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3798 );
3799 assert_eq!(
3800 disposition,
3801 TerminalDisposition::Unknown("future_disposition".to_string())
3802 );
3803 }
3804
3805 #[test]
3806 fn diagnostic_string_enums_preserve_existing_wire_names() {
3807 let names = [
3808 (RunningImageUnavailableReason::NotRunning, "not_running"),
3809 (
3810 RunningImageUnavailableReason::UnsupportedPlatform,
3811 "unsupported_platform",
3812 ),
3813 (
3814 RunningImageUnavailableReason::RunningExecutableUnreadable,
3815 "running_executable_unreadable",
3816 ),
3817 (
3818 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3819 "running_executable_permission_denied",
3820 ),
3821 (
3822 RunningImageUnavailableReason::ProcessHidden,
3823 "process_hidden",
3824 ),
3825 (
3826 RunningImageUnavailableReason::SpawnedPathUnreadable,
3827 "spawned_path_unreadable",
3828 ),
3829 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3830 (
3831 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3832 "process_identity_unconfirmed",
3833 ),
3834 ];
3835 for (value, expected) in names {
3836 let wire = serde_json::to_string(&value).unwrap();
3837 assert_eq!(wire, format!("\"{expected}\""));
3838 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3839 assert_eq!(decoded, value);
3840 }
3841
3842 for (value, expected) in [
3843 (TerminalDisposition::Stopped, "stopped"),
3844 (TerminalDisposition::Disabled, "disabled"),
3845 (TerminalDisposition::Failed, "failed"),
3846 (TerminalDisposition::Restarting, "restarting"),
3847 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3848 ] {
3849 let wire = serde_json::to_string(&value).unwrap();
3850 assert_eq!(wire, format!("\"{expected}\""));
3851 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3852 assert_eq!(decoded, value);
3853 }
3854 }
3855
3856 #[test]
3857 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3858 let entry = SupervisorEntry::new(
3859 "waiting-module",
3860 "starting",
3861 true,
3862 false,
3863 SupervisorHealthStatus::Unknown,
3864 );
3865 let old_wire = serde_json::to_value(&entry).unwrap();
3866 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3867 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3868 assert_eq!(decoded.waiting_for_previous_pid, None);
3869 let entry = entry.with_waiting_for_previous_pid(Some(42));
3870 let wire = serde_json::to_value(&entry).unwrap();
3871 assert_eq!(wire["waiting_for_previous_pid"], 42);
3872 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3873 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3874 }
3875
3876 #[test]
3877 fn diagnostic_string_enums_reject_non_string_bodies() {
3878 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3879 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3880 }
3881
3882 #[test]
3883 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3884 let body = serde_json::json!({
3885 "op": "supervisor.provenance",
3886 "daemon": {
3887 "daemon_build": {},
3888 "daemon_observed": {
3889 "running_image": {
3890 "status": "unavailable",
3891 "reason": "not_running"
3892 }
3893 }
3894 },
3895 "modules": [
3896 {
3897 "module_id": "future",
3898 "module_declared": { "status": "unverifiable" },
3899 "daemon_observed": {
3900 "running_image": {
3901 "status": "unavailable",
3902 "reason": "future_reason"
3903 }
3904 }
3905 },
3906 {
3907 "module_id": "healthy-a",
3908 "module_declared": { "status": "unverifiable" },
3909 "daemon_observed": {
3910 "running_image": {
3911 "status": "match",
3912 "evidence": {
3913 "method": "linux_proc_sha256",
3914 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3915 }
3916 }
3917 }
3918 },
3919 {
3920 "module_id": "healthy-b",
3921 "module_declared": { "status": "unverifiable" },
3922 "daemon_observed": {
3923 "running_image": {
3924 "status": "unavailable",
3925 "reason": "unsupported_platform"
3926 }
3927 }
3928 }
3929 ]
3930 });
3931
3932 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3933 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3934 panic!("decoded wrong response variant");
3935 };
3936 assert_eq!(modules.len(), 3);
3937 assert_eq!(modules[0].module_id, "future");
3938 assert_eq!(
3939 modules[0].daemon_observed.running_image,
3940 RunningImageAgreement::Unavailable {
3941 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3942 }
3943 );
3944 assert_eq!(modules[1].module_id, "healthy-a");
3945 assert_eq!(modules[2].module_id, "healthy-b");
3946 }
3947
3948 #[test]
3949 fn tagged_unknown_values_retain_tag_and_body() {
3950 macro_rules! assert_unknown_round_trip {
3951 ($ty:ident, $field:literal, $value:expr) => {
3952 let value = $value;
3953 let wire = serde_json::to_string(&value).unwrap();
3954 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3955 match decoded {
3956 $ty::Unknown { tag, body } => {
3957 assert_eq!(tag, value[$field].as_str().unwrap());
3958 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3959 }
3960 _ => panic!("decoded known variant"),
3961 }
3962 };
3963 }
3964
3965 assert_unknown_round_trip!(
3966 ModuleDeclaredProvenance,
3967 "status",
3968 serde_json::json!({"status": "future", "build": {"version": 7}})
3969 );
3970 assert_unknown_round_trip!(
3971 RunningImageAgreement,
3972 "status",
3973 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3974 );
3975 assert_unknown_round_trip!(
3976 RunningImageEvidence,
3977 "method",
3978 serde_json::json!({"method": "future", "digest": "abc"})
3979 );
3980 assert_unknown_round_trip!(
3981 SupervisorRouteConsumer,
3982 "kind",
3983 serde_json::json!({"kind": "future", "module_id": "m"})
3984 );
3985 assert_unknown_round_trip!(
3986 StderrCaptureState,
3987 "state",
3988 serde_json::json!({"state": "future", "reason": "because"})
3989 );
3990 assert_unknown_round_trip!(
3991 StderrTailEntry,
3992 "kind",
3993 serde_json::json!({"kind": "future", "text": "line"})
3994 );
3995 assert_unknown_round_trip!(
3996 ChildResourceUsage,
3997 "status",
3998 serde_json::json!({"status": "future", "memory_bytes": 1})
3999 );
4000 }
4001
4002 #[test]
4003 fn child_resource_usage_round_trips_both_known_states() {
4004 let measured = ChildResourceUsage::Measured(ChildResourceReading {
4005 memory_bytes: 0,
4006 memory_kind: ChildMemoryKind::ResidentSet,
4007 swap_bytes: Some(0),
4008 cpu_user_ms: 0,
4009 cpu_system_ms: 0,
4010 });
4011 let wire = serde_json::to_value(&measured).unwrap();
4012 assert_eq!(
4013 wire,
4014 serde_json::json!({
4015 "status": "measured",
4016 "memory_bytes": 0,
4017 "memory_kind": "resident_set",
4018 "swap_bytes": 0,
4019 "cpu_user_ms": 0,
4020 "cpu_system_ms": 0
4021 })
4022 );
4023 assert_eq!(
4024 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4025 measured
4026 );
4027
4028 let unavailable = ChildResourceUsage::Unavailable {
4029 reason: ChildResourceUnavailableReason::NotRunning,
4030 };
4031 let wire = serde_json::to_value(&unavailable).unwrap();
4032 assert_eq!(
4033 wire,
4034 serde_json::json!({"status": "unavailable", "reason": "not_running"})
4035 );
4036 assert_eq!(
4037 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4038 unavailable
4039 );
4040 }
4041
4042 #[test]
4043 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
4044 let stamped: StderrTailEntry = serde_json::from_str(
4048 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
4049 )
4050 .unwrap();
4051 assert_eq!(
4052 stamped,
4053 StderrTailEntry::Line {
4054 text: "boom".to_string(),
4055 truncated: true,
4056 at_ms: Some(1_789_801_440_685),
4057 }
4058 );
4059 let unstamped: StderrTailEntry =
4060 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
4061 assert_eq!(
4062 unstamped,
4063 StderrTailEntry::Line {
4064 text: "boom".to_string(),
4065 truncated: false,
4066 at_ms: None,
4067 }
4068 );
4069 assert_eq!(
4072 serde_json::to_string(&unstamped).unwrap(),
4073 r#"{"kind":"line","text":"boom"}"#
4074 );
4075 assert_eq!(
4076 serde_json::to_value(&stamped).unwrap()["at_ms"],
4077 serde_json::json!(1_789_801_440_685u64)
4078 );
4079 }
4080
4081 #[test]
4082 fn tagged_unknown_values_round_trip_the_original_json() {
4083 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
4084 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4085 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4086 }
4087
4088 #[test]
4089 fn tagged_unknown_values_round_trip_trailing_tag() {
4090 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
4091 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4092 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4093
4094 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
4095 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4096 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4097 }
4098
4099 #[test]
4100 fn tagged_unknown_values_round_trip_middle_tag() {
4101 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
4102 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4103 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4104
4105 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
4106 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4107 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4108 }
4109
4110 #[test]
4111 fn tagged_unknown_values_round_trip_deep_payload() {
4112 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
4113 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4114 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4115
4116 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
4117 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4118 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4119 }
4120
4121 #[test]
4122 fn tagged_unknown_values_reject_non_object_bodies() {
4123 for wire in ["42", r#""future""#, "[]"] {
4124 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
4125 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
4126 }
4127 }
4128
4129 #[test]
4130 fn duplicate_discriminators_reject_without_panicking() {
4131 assert_eq!(
4132 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
4133 .unwrap(),
4134 ModuleDeclaredProvenance::Unverifiable
4135 );
4136 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
4137 .unwrap()
4138 {
4139 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
4140 _ => panic!("future discriminator decoded as a known variant"),
4141 }
4142
4143 let wires = [
4144 r#"{"status":"reported","status":"unverifiable"}"#,
4145 r#"{"status":"unverifiable","status":"reported"}"#,
4146 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4147 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4148 ];
4149
4150 for wire in wires {
4151 let result =
4152 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4153 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4154 assert!(
4155 result.unwrap().is_err(),
4156 "duplicate discriminator decoded: {wire}"
4157 );
4158 }
4159
4160 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4161 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4162 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4163 assert!(
4164 result.unwrap().is_err(),
4165 "duplicate discriminator decoded: {wire}"
4166 );
4167 }
4168
4169 #[test]
4170 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4171 let known_wire =
4172 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4173 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4174 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4175
4176 for wire in [
4177 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4178 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4179 ] {
4180 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4181 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4182 }
4183
4184 for wire in [
4185 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4186 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4187 ] {
4188 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4189 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4190 }
4191
4192 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4193 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4194 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4195
4196 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4197 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4198 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4199 }
4200
4201 #[test]
4202 fn tagged_unknown_member_does_not_discard_known_siblings() {
4203 let body = serde_json::json!({
4204 "modules": [{
4205 "module_id": "target",
4206 "routes": [
4207 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4208 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4209 ]
4210 }]
4211 });
4212 let decoded: ClientControlResponse = serde_json::from_value(
4213 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4214 )
4215 .unwrap();
4216 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4217 panic!("decoded wrong response variant");
4218 };
4219 assert_eq!(modules[0].routes.len(), 2);
4220 assert_eq!(
4221 modules[0].routes[1].consumer,
4222 SupervisorRouteConsumer::Direct { connection_id: 7 }
4223 );
4224 }
4225}
4226
4227#[cfg(test)]
4228mod launch_nonce_redaction_tests {
4229 use super::*;
4230
4231 const NONCE: &str = "nonce-f00dfeed1234abcd";
4232
4233 fn identity() -> ConsumerIdentity {
4234 ConsumerIdentity {
4235 module_id: "wernicke".to_string(),
4236 launch_nonce: NONCE.to_string(),
4237 }
4238 }
4239
4240 #[test]
4241 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4242 let printed = format!("{:?}", identity());
4243 assert!(printed.contains("wernicke"), "{printed}");
4244 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4245 }
4246
4247 #[test]
4248 fn route_open_request_debug_never_prints_the_nonce() {
4249 let request = ClientControlRequest::RouteOpen {
4250 busy_refusals: None,
4251 target: subc_protocol::RouteTarget::ToolProvider {
4252 module_id: "broca".to_string(),
4253 },
4254 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4255 consumer_identity: Some(identity()),
4256 consumer_capabilities: None,
4257 role_versions: None,
4258 admission_facts: None,
4259 scope: None,
4260 };
4261 let printed = format!("{request:?}");
4262 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4263 }
4264}
4265
4266#[cfg(test)]
4267mod reader_skew_tests {
4268 use super::*;
4269 use serde_json::{json, Value};
4270
4271 fn catalog() -> Value {
4272 json!({"module_id": "provider", "roles": [], "control_ops": []})
4273 }
4274
4275 fn reply() -> Value {
4276 json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4277 }
4278
4279 fn target() -> Value {
4280 json!({
4281 "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4282 "authority_epoch": 23, "first_party": true,
4283 "approved_declarations_digest": "approved"
4284 })
4285 }
4286
4287 fn request() -> Value {
4288 json!({
4289 "op": "route.open",
4290 "target": {"kind": "tool_provider", "module_id": "provider"},
4291 "identity": {"harness": "test", "session": "session-1"}
4292 })
4293 }
4294
4295 #[test]
4296 fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4297 let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4298 let built = CatalogEntry::new("provider", vec![], vec![]);
4299 assert_eq!(old, built);
4300 assert_eq!(old.first_party, None);
4301 let old_bytes = serde_json::to_value(&old).unwrap();
4302 let additions = json!({
4303 "incarnation": "daemon", "spawn": 17, "first_party": false,
4304 "origin": "development", "requested_declarations_digest": "requested",
4305 "approved_declarations_digest": "approved"
4306 });
4307 let mut body = catalog();
4308 for (key, value) in additions.as_object().unwrap() {
4309 assert!(old_bytes.get(key).is_none(), "{key}");
4310 body[key] = value.clone();
4311 }
4312 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4313 let encoded = serde_json::to_value(&decoded).unwrap();
4314 for (key, value) in additions.as_object().unwrap() {
4315 assert_eq!(&encoded[key], value, "{key}");
4316 }
4317 assert_eq!(decoded.first_party, Some(false));
4318 assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4319 }
4320
4321 #[test]
4322 fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4323 let mut body = catalog();
4324 body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4325 body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4326 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4327 let encoded = serde_json::to_value(decoded).unwrap();
4328 for key in ["requested_declarations", "approved_declarations"] {
4329 assert_eq!(encoded[key], body[key]);
4330 }
4331 let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4332 assert_eq!(unfiltered.approved_declarations, None);
4333 assert_eq!(unfiltered.requested_declarations, None);
4334 }
4335
4336 #[test]
4337 fn reader_skew_catalog_unknown_origin_is_other() {
4338 let mut body = catalog();
4339 body["origin"] = json!("future-origin");
4340 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4341 assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4342 }
4343
4344 #[test]
4345 fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4346 let mut body = catalog();
4347 body["spawn"] = json!(9_007_199_254_740_991_u64);
4348 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4349 assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4350 for invalid in [
4351 json!(9_007_199_254_740_992_u64),
4352 json!(-1),
4353 json!(1.5),
4354 json!("17"),
4355 ] {
4356 body["spawn"] = invalid;
4357 assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4358 }
4359 }
4360
4361 #[test]
4362 fn reader_skew_catalog_watch_request_uses_subscription_op() {
4363 let body = json!({"op": "catalog.watch"});
4364 let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4365 assert_eq!(request, CatalogWatchRequest::new());
4366 assert_eq!(serde_json::to_value(request).unwrap(), body);
4367 assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4368 for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4369 assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4370 }
4371 }
4372
4373 #[test]
4374 fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4375 for generation in [0, 19, 42] {
4376 let body = json!({"op": "catalog.watch", "generation": generation});
4377 let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4378 assert_eq!(push, CatalogWatchResponse::new(generation));
4379 assert_eq!(serde_json::to_value(push).unwrap(), body);
4380 }
4381 assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4382 for invalid in [
4383 json!({"op": "catalog.watch"}),
4384 json!({"op": "activity.subscribe", "generation": 1}),
4385 ] {
4386 assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4387 }
4388 }
4389
4390 #[test]
4391 fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4392 let mut body = reply();
4393 let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4394 let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4395 assert_eq!(empty, RouteOpenReplyExt::new());
4396 empty.write_to(&mut body).unwrap();
4397 assert_eq!(body, reply());
4398 body["target"] = target();
4399 let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4400 assert_eq!(
4401 decoded.target.as_ref().unwrap().kind,
4402 RouteOpenTargetKind::Spawn
4403 );
4404 let mut encoded = reply();
4405 RouteOpenReplyExt::new()
4406 .with_target(decoded.target)
4407 .write_to(&mut encoded)
4408 .unwrap();
4409 assert_eq!(encoded, body);
4410 assert_eq!(
4411 serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4412 legacy
4413 );
4414 RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4415 assert_eq!(encoded, reply());
4416 }
4417
4418 #[test]
4419 fn reader_skew_route_open_incomplete_target_is_unmarked() {
4420 let mut body = reply();
4421 body["target"] = target();
4422 assert!(RouteOpenReplyExt::read_from(&body)
4423 .unwrap()
4424 .target
4425 .is_some());
4426 for key in [
4427 "incarnation",
4428 "kind",
4429 "spawn",
4430 "authority_epoch",
4431 "first_party",
4432 "approved_declarations_digest",
4433 ] {
4434 let mut incomplete = body.clone();
4435 incomplete["target"].as_object_mut().unwrap().remove(key);
4436 assert_eq!(
4437 RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4438 None,
4439 "{key}"
4440 );
4441 }
4442 body["target"] = Value::Null;
4443 assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4444 }
4445
4446 #[test]
4447 fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4448 for (kind, expected) in [
4449 ("prefix", RouteOpenTargetKind::Prefix),
4450 ("unsupervised", RouteOpenTargetKind::Unsupervised),
4451 ] {
4452 let mut body = reply();
4453 body["target"] = target();
4454 body["target"]["kind"] = json!(kind);
4455 body["target"]["spawn"] = json!("not-a-spawn");
4457 body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4458 body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4459 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4460 let target = ext.target.as_ref().unwrap();
4461 assert_eq!(target.kind, expected);
4462 assert_eq!(target.spawn, None);
4463 assert_eq!(target.authority_epoch, None);
4464 assert_eq!(target.approved_declarations_digest, None);
4465 assert!(!target.first_party);
4466 let mut encoded = reply();
4467 ext.write_to(&mut encoded).unwrap();
4468 for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
4469 assert!(encoded["target"].get(key).is_none());
4470 }
4471 }
4472 }
4473
4474 #[test]
4475 fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4476 let mut body = reply();
4477 body["target"] = target();
4478 body["target"]["kind"] = json!("future-kind");
4479 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4480 let target = ext.target.unwrap();
4481 assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4482 assert_eq!(target.spawn, None);
4483 assert_eq!(target.authority_epoch, None);
4484 assert_eq!(target.approved_declarations_digest, None);
4485 assert!(!target.first_party);
4486 }
4487
4488 #[test]
4489 fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4490 for field in ["spawn", "authority_epoch"] {
4491 let mut body = reply();
4492 body["target"] = target();
4493 body["target"][field] = json!(9_007_199_254_740_991_u64);
4494 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4495 assert_eq!(
4496 serde_json::to_value(ext).unwrap()["target"][field],
4497 9_007_199_254_740_991_u64
4498 );
4499 for invalid in [
4500 json!(9_007_199_254_740_992_u64),
4501 json!(-1),
4502 json!(1.5),
4503 json!("17"),
4504 ] {
4505 body["target"][field] = invalid;
4506 assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4507 let mut incomplete = body.clone();
4508 incomplete["target"]
4509 .as_object_mut()
4510 .unwrap()
4511 .remove("incarnation");
4512 assert!(
4513 RouteOpenReplyExt::read_from(&incomplete).is_err(),
4514 "{field}"
4515 );
4516 }
4517 }
4518 }
4519
4520 #[test]
4521 fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4522 let mut body = request();
4523 let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4524 assert_eq!(
4525 RouteOpenRequestExt::read_from(&body).unwrap(),
4526 RouteOpenRequestExt::new()
4527 );
4528 RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4529 assert_eq!(body, request());
4530 body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4531 let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4532 assert_eq!(
4533 decoded.accepts_close_reasons,
4534 Some(vec!["authority_changed".into(), "future-reason".into()])
4535 );
4536 let mut encoded = request();
4537 RouteOpenRequestExt::new()
4538 .with_accepts_close_reasons(decoded.accepts_close_reasons)
4539 .write_to(&mut encoded)
4540 .unwrap();
4541 assert_eq!(encoded, body);
4542 assert_eq!(
4543 serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4544 legacy
4545 );
4546 RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4547 assert_eq!(encoded, request());
4548 assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4549 }
4550
4551 #[test]
4552 fn reader_skew_route_open_helpers_refuse_other_bodies() {
4553 for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4554 assert!(RouteOpenRequestExt::read_from(&body).is_err());
4555 assert!(RouteOpenReplyExt::read_from(&body).is_err());
4556 assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4557 assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4558 }
4559 }
4560
4561 #[test]
4562 fn reader_skew_route_open_target_constructor_validates_like_reader() {
4563 let spawn = RouteOpenTarget::new(
4564 "daemon",
4565 RouteOpenTargetKind::Spawn,
4566 Some(17),
4567 Some(23),
4568 true,
4569 Some("approved".into()),
4570 )
4571 .unwrap();
4572 assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4573 for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4574 assert!(RouteOpenTarget::new(
4575 "daemon",
4576 RouteOpenTargetKind::Spawn,
4577 Some(spawn),
4578 Some(epoch),
4579 true,
4580 Some("approved".into())
4581 )
4582 .is_err());
4583 }
4584 }
4585}
4586
4587#[cfg(test)]
4588mod claim_wire_tests {
4589 use super::*;
4590 use serde_json::{json, Value};
4591
4592 fn legacy_provenance() -> SupervisorModuleProvenance {
4593 SupervisorModuleProvenance {
4594 module_id: "worker".into(),
4595 module_declared: ModuleDeclaredProvenance::Unverifiable,
4596 daemon_observed: SupervisorObservedProcess {
4597 launch_nonce_source: None,
4598 pid: None,
4599 spawned_at_ms: None,
4600 spawned_from: None,
4601 running_image: RunningImageAgreement::Unavailable {
4602 reason: RunningImageUnavailableReason::NotRunning,
4603 },
4604 },
4605 }
4606 }
4607
4608 #[test]
4609 fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4610 let legacy = legacy_provenance();
4611 let original = serde_json::to_value(&legacy).unwrap();
4612 let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4613 assert_eq!(absent.registration, None);
4614 let mut wire = original.clone();
4615 absent.write_to(&mut wire).unwrap();
4616 assert_eq!(wire, original);
4617 for (method, spelling) in [
4618 (RegistrationMethod::Channel, "channel"),
4619 (RegistrationMethod::Nonce, "nonce"),
4620 ] {
4621 let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4622 ext.write_to(&mut wire).unwrap();
4623 assert_eq!(wire["registration"], spelling);
4624 assert_eq!(
4625 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4626 ext
4627 );
4628 let old_reader: SupervisorModuleProvenance =
4629 serde_json::from_value(wire.clone()).unwrap();
4630 assert_eq!(old_reader, legacy);
4631 assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4632 }
4633 absent.write_to(&mut wire).unwrap();
4634 assert_eq!(wire, original);
4635 for mut invalid in [Value::Null, json!([]), json!("entry")] {
4636 assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4637 assert!(absent.write_to(&mut invalid).is_err());
4638 }
4639 }
4640
4641 #[test]
4642 fn provenance_unknown_registration_is_not_channel_or_nonce() {
4643 let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4644 wire["registration"] = json!("future_method");
4645 let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4646 assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4647 assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4648 assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4649 wire["registration"] = json!(false);
4650 assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4651 }
4652
4653 #[test]
4654 fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4655 let original = serde_json::to_value(legacy_provenance()).unwrap();
4656 for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4657 let mut golden = original.clone();
4658 golden["registration_declaration"] = json!(declaration);
4659 let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4660 assert_eq!(
4661 serde_json::to_value(&extension).unwrap(),
4662 json!({
4663 "registration_declaration": declaration
4664 })
4665 );
4666 let mut written = original.clone();
4667 extension.write_to(&mut written).unwrap();
4668 assert_eq!(written, golden);
4669 assert_eq!(
4670 serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4671 legacy_provenance()
4672 );
4673 SupervisorModuleProvenanceExt::new()
4674 .write_to(&mut written)
4675 .unwrap();
4676 assert_eq!(written, original);
4677 }
4678 }
4679
4680 #[test]
4681 fn admission_refusal_is_optional_and_open() {
4682 let entry = SupervisorEntry::new(
4683 "worker",
4684 "stopped",
4685 true,
4686 false,
4687 SupervisorHealthStatus::Unknown,
4688 );
4689 let original = serde_json::to_value(&entry).unwrap();
4690 assert!(original.get("admission_refused").is_none());
4691 let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
4692 assert_eq!(read.admission_refused, None);
4693 assert_eq!(serde_json::to_value(read).unwrap(), original);
4694 assert_eq!(
4695 REGISTRATION_CHANNEL_UNSUPPORTED,
4696 "registration_channel_unsupported"
4697 );
4698 for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
4699 let mut wire = original.clone();
4700 wire["admission_refused"] = json!(reason);
4701 let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
4702 assert_eq!(read.admission_refused.as_deref(), Some(reason));
4703 assert_eq!(serde_json::to_value(read).unwrap(), wire);
4704 let built = entry.clone().with_admission_refused(Some(reason.into()));
4705 assert_eq!(serde_json::to_value(built).unwrap(), wire);
4706 }
4707 }
4708}