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 #[serde(default, skip_serializing_if = "Option::is_none")]
1068 pub waiting_for_previous_detail: Option<String>,
1069}
1070
1071impl SupervisorModuleProvenanceExt {
1072 pub fn new() -> Self {
1073 Self::default()
1074 }
1075
1076 #[must_use]
1077 pub fn with_registration(mut self, registration: Option<RegistrationMethod>) -> Self {
1078 self.registration = registration;
1079 self
1080 }
1081
1082 #[must_use]
1083 pub fn with_waiting_for_previous_detail(mut self, detail: Option<String>) -> Self {
1084 self.waiting_for_previous_detail = detail;
1085 self
1086 }
1087
1088 pub fn read_from(entry: &serde_json::Value) -> serde_json::Result<Self> {
1090 if !entry.is_object() {
1091 return Err(serde_json::Error::custom(
1092 "expected a module provenance entry object",
1093 ));
1094 }
1095 serde_json::from_value(entry.clone())
1096 }
1097
1098 pub fn write_to(&self, entry: &mut serde_json::Value) -> serde_json::Result<()> {
1101 let object = entry.as_object_mut().ok_or_else(|| {
1102 serde_json::Error::custom("expected a module provenance entry object")
1103 })?;
1104 object.remove("registration");
1105 if let Some(method) = &self.registration {
1106 object.insert("registration".into(), serde_json::to_value(method)?);
1107 }
1108 object.remove("registration_declaration");
1109 if let Some(declaration) = &self.registration_declaration {
1110 object.insert(
1111 "registration_declaration".into(),
1112 declaration.clone().into(),
1113 );
1114 }
1115 object.remove("waiting_for_previous_detail");
1116 if let Some(detail) = &self.waiting_for_previous_detail {
1117 object.insert("waiting_for_previous_detail".into(), detail.clone().into());
1118 }
1119 Ok(())
1120 }
1121}
1122
1123#[non_exhaustive]
1126#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1127#[serde(rename_all = "snake_case")]
1128pub enum RegistrationMethod {
1129 Channel,
1130 Nonce,
1131 #[serde(other)]
1132 Unknown,
1133}
1134
1135pub const REGISTRATION_CHANNEL_UNSUPPORTED: &str = "registration_channel_unsupported";
1138
1139#[derive(Debug, Clone, PartialEq)]
1141pub enum ModuleDeclaredProvenance {
1142 Reported {
1143 build: ManifestProvenance,
1144 },
1145 Unverifiable,
1146 Unknown {
1149 tag: String,
1150 body: OrderedJsonObject,
1151 },
1152}
1153
1154#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1159pub struct SupervisorObservedProcess {
1160 #[serde(default, skip_serializing_if = "Option::is_none")]
1166 pub launch_nonce_source: Option<String>,
1167 #[serde(default, skip_serializing_if = "Option::is_none")]
1168 pub pid: Option<u32>,
1169 #[serde(default, skip_serializing_if = "Option::is_none")]
1170 pub spawned_at_ms: Option<u64>,
1171 #[serde(default, skip_serializing_if = "Option::is_none")]
1172 pub spawned_from: Option<PathBuf>,
1173 pub running_image: RunningImageAgreement,
1174}
1175
1176#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1193#[non_exhaustive]
1194pub struct PendingReloadVerdict {
1195 pub path: ReloadPathAgreement,
1196 pub image: RunningImageAgreement,
1197 #[serde(default, skip_serializing_if = "Option::is_none")]
1198 pub spec: Option<LaunchSpecAgreement>,
1199}
1200
1201impl PendingReloadVerdict {
1202 #[must_use]
1204 pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
1205 Self {
1206 path,
1207 image,
1208 spec: None,
1209 }
1210 }
1211
1212 #[must_use]
1214 pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
1215 self.spec = spec;
1216 self
1217 }
1218}
1219
1220#[cfg(test)]
1221mod launch_spec_wire_tests {
1222 use super::*;
1223
1224 #[test]
1225 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
1226 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
1227 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
1228 assert_eq!(parsed.spec, None);
1229 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
1230 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
1231 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
1232 assert!(
1233 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
1234 );
1235 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
1236 let unavailable = LaunchSpecAgreement::Unavailable {
1237 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
1238 };
1239 let encoded = serde_json::to_string(&unavailable).unwrap();
1240 assert_eq!(
1241 encoded,
1242 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
1243 );
1244 assert_eq!(
1245 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
1246 unavailable
1247 );
1248 }
1249}
1250
1251#[derive(Debug, Clone, PartialEq)]
1254pub enum LaunchSpecAgreement {
1255 Match,
1256 Mismatch,
1257 Unavailable {
1258 reason: LaunchSpecUnavailableReason,
1259 },
1260 Unknown {
1261 tag: String,
1262 body: OrderedJsonObject,
1263 },
1264}
1265
1266open_string_enum! {
1267 LaunchSpecUnavailableReason {
1268 NotRunning => "not_running",
1269 SpawnedSpecUnavailable => "spawned_spec_unavailable",
1270 }
1271}
1272
1273#[derive(Debug, Clone, PartialEq)]
1275pub enum ReloadPathAgreement {
1276 Match,
1277 Mismatch {
1278 configured: PathBuf,
1279 spawned_from: PathBuf,
1280 },
1281 Unavailable {
1282 reason: ReloadPathUnavailableReason,
1283 },
1284 Unknown {
1285 tag: String,
1286 body: OrderedJsonObject,
1287 },
1288}
1289
1290open_string_enum! {
1291 ReloadPathUnavailableReason {
1293 NotRunning => "not_running",
1294 SpawnedPathUnavailable => "spawned_path_unavailable",
1295 }
1296}
1297
1298#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1300pub struct SupervisorDaemonProvenance {
1301 pub daemon_build: DaemonBuildProvenance,
1302 pub daemon_observed: DaemonObservedProcess,
1303}
1304
1305#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1307pub struct DaemonBuildProvenance {
1308 #[serde(default, skip_serializing_if = "Option::is_none")]
1309 pub build_git_sha: Option<String>,
1310 #[serde(default, skip_serializing_if = "Option::is_none")]
1311 pub build_lock_digest: Option<String>,
1312}
1313
1314#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1316pub struct DaemonObservedProcess {
1317 #[serde(default, skip_serializing_if = "Option::is_none")]
1318 pub pid: Option<u32>,
1319 #[serde(default, skip_serializing_if = "Option::is_none")]
1324 pub started_at_ms: Option<u64>,
1325 pub running_image: RunningImageAgreement,
1326}
1327
1328#[derive(Debug, Clone, PartialEq)]
1330pub enum RunningImageAgreement {
1331 Match {
1332 evidence: RunningImageEvidence,
1333 },
1334 Mismatch {
1335 running: RunningImageEvidence,
1336 disk: RunningImageEvidence,
1337 },
1338 Unavailable {
1339 reason: RunningImageUnavailableReason,
1340 },
1341 Unknown {
1344 tag: String,
1345 body: OrderedJsonObject,
1346 },
1347}
1348
1349#[derive(Debug, Clone, PartialEq)]
1351pub enum RunningImageEvidence {
1352 LinuxProcSha256 {
1353 digest: String,
1354 },
1355 MacosSpawnInode {
1356 device: u64,
1357 inode: u64,
1358 },
1359 WindowsSpawnFileId {
1361 volume_serial_number: u64,
1362 file_id: [u8; 16],
1363 },
1364 Unknown {
1367 tag: String,
1368 body: OrderedJsonObject,
1369 },
1370}
1371
1372open_string_enum! {
1373 RunningImageUnavailableReason {
1375 NotRunning => "not_running",
1376 NotYetMeasured => "not_yet_measured",
1377 UnsupportedPlatform => "unsupported_platform",
1378 RunningExecutableUnreadable => "running_executable_unreadable",
1379 RunningExecutablePermissionDenied => "running_executable_permission_denied",
1380 ProcessHidden => "process_hidden",
1381 SpawnedPathUnreadable => "spawned_path_unreadable",
1382 HashFailed => "hash_failed",
1383 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
1384 }
1385}
1386
1387#[derive(Debug, Clone, PartialEq)]
1393pub enum SupervisorRouteConsumer {
1394 Reserved {
1395 module_id: String,
1396 },
1397 Direct {
1398 connection_id: u64,
1399 },
1400 Unknown {
1403 tag: String,
1404 body: OrderedJsonObject,
1405 },
1406}
1407
1408#[derive(Debug, Clone, PartialEq)]
1415pub enum StderrCaptureState {
1416 Captured,
1419 Incomplete { reason: String },
1421 NotCaptured { reason: String },
1423 Unknown {
1426 tag: String,
1427 body: OrderedJsonObject,
1428 },
1429}
1430
1431#[derive(Debug, Clone, PartialEq)]
1432pub enum StderrTailEntry {
1433 Line {
1434 text: String,
1435 truncated: bool,
1440 at_ms: Option<u64>,
1444 },
1445 ProcessStart,
1450 Unknown {
1453 tag: String,
1454 body: OrderedJsonObject,
1455 },
1456}
1457
1458#[derive(Debug, Serialize, Deserialize)]
1459#[serde(tag = "status", rename_all = "snake_case")]
1460enum ModuleDeclaredProvenanceWire {
1461 Reported { build: ManifestProvenance },
1462 Unverifiable,
1463}
1464
1465#[derive(Debug, Serialize, Deserialize)]
1466#[serde(tag = "status", rename_all = "snake_case")]
1467enum RunningImageAgreementWire {
1468 Match {
1469 evidence: RunningImageEvidence,
1470 },
1471 Mismatch {
1472 running: RunningImageEvidence,
1473 disk: RunningImageEvidence,
1474 },
1475 Unavailable {
1476 reason: RunningImageUnavailableReason,
1477 },
1478}
1479
1480#[derive(Debug, Serialize, Deserialize)]
1481#[serde(tag = "status", rename_all = "snake_case")]
1482enum ReloadPathAgreementWire {
1483 Match,
1484 Mismatch {
1485 configured: PathBuf,
1486 spawned_from: PathBuf,
1487 },
1488 Unavailable {
1489 reason: ReloadPathUnavailableReason,
1490 },
1491}
1492
1493#[derive(Debug, Serialize, Deserialize)]
1494#[serde(tag = "status", rename_all = "snake_case")]
1495enum LaunchSpecAgreementWire {
1496 Match,
1497 Mismatch,
1498 Unavailable { reason: LaunchSpecUnavailableReason },
1499}
1500
1501#[derive(Debug, Serialize, Deserialize)]
1502#[serde(tag = "method", rename_all = "snake_case")]
1503enum RunningImageEvidenceWire {
1504 LinuxProcSha256 {
1505 digest: String,
1506 },
1507 MacosSpawnInode {
1508 device: u64,
1509 inode: u64,
1510 },
1511 WindowsSpawnFileId {
1512 volume_serial_number: u64,
1513 file_id: [u8; 16],
1514 },
1515}
1516
1517#[derive(Debug, Serialize, Deserialize)]
1518#[serde(tag = "kind", rename_all = "snake_case")]
1519enum SupervisorRouteConsumerWire {
1520 Reserved { module_id: String },
1521 Direct { connection_id: u64 },
1522}
1523
1524#[derive(Debug, Serialize, Deserialize)]
1525#[serde(tag = "state", rename_all = "snake_case")]
1526enum StderrCaptureStateWire {
1527 Captured,
1528 Incomplete { reason: String },
1529 NotCaptured { reason: String },
1530}
1531
1532#[derive(Debug, Serialize, Deserialize)]
1533#[serde(tag = "status", rename_all = "snake_case")]
1534enum ChildResourceUsageWire {
1535 Measured(ChildResourceReading),
1536 Unavailable {
1537 reason: ChildResourceUnavailableReason,
1538 },
1539}
1540
1541#[derive(Debug, Serialize, Deserialize)]
1542#[serde(tag = "kind", rename_all = "snake_case")]
1543enum StderrTailEntryWire {
1544 Line {
1545 text: String,
1546 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1547 truncated: bool,
1548 #[serde(default, skip_serializing_if = "Option::is_none")]
1551 at_ms: Option<u64>,
1552 },
1553 ProcessStart,
1554}
1555
1556#[derive(Debug, Clone, PartialEq)]
1558pub enum OrderedJsonValue {
1559 Null,
1560 Bool(bool),
1561 Number(serde_json::Number),
1562 String(String),
1563 Array(Vec<Self>),
1564 Object(OrderedJsonObject),
1565}
1566
1567#[derive(Debug, Clone, PartialEq)]
1569pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1570
1571impl OrderedJsonObject {
1572 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1574 &self.0
1575 }
1576
1577 fn into_value(self) -> serde_json::Value {
1578 serde_json::Value::Object(
1579 self.0
1580 .into_iter()
1581 .map(|(key, value)| (key, value.into_value()))
1582 .collect(),
1583 )
1584 }
1585}
1586
1587impl OrderedJsonValue {
1588 fn into_value(self) -> serde_json::Value {
1589 match self {
1590 Self::Null => serde_json::Value::Null,
1591 Self::Bool(value) => serde_json::Value::Bool(value),
1592 Self::Number(value) => serde_json::Value::Number(value),
1593 Self::String(value) => serde_json::Value::String(value),
1594 Self::Array(values) => {
1595 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1596 }
1597 Self::Object(value) => value.into_value(),
1598 }
1599 }
1600}
1601
1602impl Serialize for OrderedJsonValue {
1603 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1604 where
1605 S: Serializer,
1606 {
1607 match self {
1608 Self::Null => serializer.serialize_unit(),
1609 Self::Bool(value) => serializer.serialize_bool(*value),
1610 Self::Number(value) => value.serialize(serializer),
1611 Self::String(value) => serializer.serialize_str(value),
1612 Self::Array(values) => values.serialize(serializer),
1613 Self::Object(value) => value.serialize(serializer),
1614 }
1615 }
1616}
1617
1618impl<'de> Deserialize<'de> for OrderedJsonValue {
1619 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1620 where
1621 D: Deserializer<'de>,
1622 {
1623 struct OrderedValueVisitor;
1624
1625 impl<'de> Visitor<'de> for OrderedValueVisitor {
1626 type Value = OrderedJsonValue;
1627
1628 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1629 formatter.write_str("a JSON value with ordered object members")
1630 }
1631
1632 fn visit_unit<E>(self) -> Result<Self::Value, E>
1633 where
1634 E: serde::de::Error,
1635 {
1636 Ok(OrderedJsonValue::Null)
1637 }
1638
1639 fn visit_none<E>(self) -> Result<Self::Value, E>
1640 where
1641 E: serde::de::Error,
1642 {
1643 Ok(OrderedJsonValue::Null)
1644 }
1645
1646 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1647 where
1648 D: Deserializer<'de>,
1649 {
1650 OrderedJsonValue::deserialize(deserializer)
1651 }
1652
1653 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1654 where
1655 E: serde::de::Error,
1656 {
1657 Ok(OrderedJsonValue::Bool(value))
1658 }
1659
1660 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1661 where
1662 E: serde::de::Error,
1663 {
1664 Ok(OrderedJsonValue::Number(value.into()))
1665 }
1666
1667 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1668 where
1669 E: serde::de::Error,
1670 {
1671 Ok(OrderedJsonValue::Number(value.into()))
1672 }
1673
1674 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1675 where
1676 E: serde::de::Error,
1677 {
1678 serde_json::Number::from_f64(value)
1679 .map(OrderedJsonValue::Number)
1680 .ok_or_else(|| E::custom("non-finite JSON number"))
1681 }
1682
1683 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1684 where
1685 E: serde::de::Error,
1686 {
1687 Ok(OrderedJsonValue::String(value.to_owned()))
1688 }
1689
1690 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1691 where
1692 E: serde::de::Error,
1693 {
1694 Ok(OrderedJsonValue::String(value))
1695 }
1696
1697 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1698 where
1699 A: SeqAccess<'de>,
1700 {
1701 let mut values = Vec::new();
1702 while let Some(value) = sequence.next_element()? {
1703 values.push(value);
1704 }
1705 Ok(OrderedJsonValue::Array(values))
1706 }
1707
1708 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1709 where
1710 A: MapAccess<'de>,
1711 {
1712 let mut entries = Vec::new();
1713 while let Some((key, value)) = map.next_entry()? {
1714 entries.push((key, value));
1715 }
1716 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1717 }
1718 }
1719
1720 deserializer.deserialize_any(OrderedValueVisitor)
1721 }
1722}
1723
1724impl Serialize for OrderedJsonObject {
1725 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1726 where
1727 S: Serializer,
1728 {
1729 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1730 for (key, value) in &self.0 {
1731 map.serialize_entry(key, value)?;
1732 }
1733 map.end()
1734 }
1735}
1736
1737impl<'de> Deserialize<'de> for OrderedJsonObject {
1738 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1739 where
1740 D: Deserializer<'de>,
1741 {
1742 struct OrderedObjectVisitor;
1743
1744 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1745 type Value = OrderedJsonObject;
1746
1747 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1748 formatter.write_str("an object with ordered JSON members")
1749 }
1750
1751 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1752 where
1753 A: MapAccess<'de>,
1754 {
1755 let mut entries = Vec::new();
1756 while let Some((key, value)) = map.next_entry()? {
1757 entries.push((key, value));
1758 }
1759 Ok(OrderedJsonObject(entries))
1760 }
1761 }
1762
1763 deserializer.deserialize_map(OrderedObjectVisitor)
1764 }
1765}
1766
1767fn read_tagged<'de, D>(
1768 deserializer: D,
1769 field: &'static str,
1770) -> Result<(String, OrderedJsonObject), D::Error>
1771where
1772 D: Deserializer<'de>,
1773{
1774 let body = OrderedJsonObject::deserialize(deserializer)?;
1775 let mut tag = None;
1776 for (key, value) in body.as_entries() {
1777 if key != field {
1778 continue;
1779 }
1780 if tag.is_some() {
1781 return Err(D::Error::custom(format!(
1782 "tagged object has duplicate `{field}` field"
1783 )));
1784 }
1785 let OrderedJsonValue::String(value) = value else {
1786 return Err(D::Error::custom(format!(
1787 "tagged object has no string `{field}` field"
1788 )));
1789 };
1790 tag = Some(value);
1791 }
1792 let Some(tag) = tag else {
1793 return Err(D::Error::custom(format!(
1794 "tagged object has no string `{field}` field"
1795 )));
1796 };
1797 Ok((tag.to_string(), body))
1798}
1799
1800fn read_ordered_tagged(
1801 value: OrderedJsonValue,
1802 field: &'static str,
1803) -> Result<(String, OrderedJsonObject), String> {
1804 let OrderedJsonValue::Object(body) = value else {
1805 return Err(format!("expected tagged object with `{field}` field"));
1806 };
1807 let mut tag = None;
1808 for (key, value) in body.as_entries() {
1809 if key != field {
1810 continue;
1811 }
1812 if tag.is_some() {
1813 return Err(format!("tagged object has duplicate `{field}` field"));
1814 }
1815 let OrderedJsonValue::String(value) = value else {
1816 return Err(format!("tagged object has no string `{field}` field"));
1817 };
1818 tag = Some(value);
1819 }
1820 let Some(tag) = tag else {
1821 return Err(format!("tagged object has no string `{field}` field"));
1822 };
1823 Ok((tag.to_string(), body))
1824}
1825
1826fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1827 body.as_entries()
1828 .iter()
1829 .find_map(|(key, value)| (key == field).then_some(value))
1830}
1831
1832fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1833 match ordered_field(body, field) {
1834 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1835 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1836 None => Err(format!("tagged object has no `{field}` field")),
1837 }
1838}
1839
1840fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1841 let (tag, body) = read_ordered_tagged(value, "method")?;
1842 match tag.as_str() {
1843 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1844 digest: ordered_string(&body, "digest")?,
1845 }),
1846 "macos_spawn_inode" => {
1847 let device = ordered_field(&body, "device")
1848 .and_then(|value| match value {
1849 OrderedJsonValue::Number(number) => number.as_u64(),
1850 _ => None,
1851 })
1852 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1853 let inode = ordered_field(&body, "inode")
1854 .and_then(|value| match value {
1855 OrderedJsonValue::Number(number) => number.as_u64(),
1856 _ => None,
1857 })
1858 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1859 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1860 }
1861 "windows_spawn_file_id" => {
1862 let wire: RunningImageEvidenceWire = serde_json::from_value(
1863 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1864 )
1865 .map_err(|error| error.to_string())?;
1866 match wire {
1867 RunningImageEvidenceWire::WindowsSpawnFileId {
1868 volume_serial_number,
1869 file_id,
1870 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1871 volume_serial_number,
1872 file_id,
1873 }),
1874 _ => unreachable!(),
1875 }
1876 }
1877 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1878 }
1879}
1880
1881impl Serialize for ModuleDeclaredProvenance {
1882 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1883 where
1884 S: Serializer,
1885 {
1886 match self {
1887 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1888 build: build.clone(),
1889 }
1890 .serialize(serializer),
1891 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1892 Self::Unknown { body, .. } => body.serialize(serializer),
1893 }
1894 }
1895}
1896
1897impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1898 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1899 where
1900 D: serde::Deserializer<'de>,
1901 {
1902 let (tag, value) = read_tagged(deserializer, "status")?;
1903 match tag.as_str() {
1904 "reported" => match serde_json::from_value(value.into_value())
1905 .map_err(D::Error::custom)?
1906 {
1907 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1908 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1909 },
1910 "unverifiable" => {
1911 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1912 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1913 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1914 }
1915 }
1916 _ => Ok(Self::Unknown { tag, body: value }),
1917 }
1918 }
1919}
1920
1921impl Serialize for RunningImageAgreement {
1922 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1923 where
1924 S: Serializer,
1925 {
1926 match self {
1927 Self::Match { evidence } => RunningImageAgreementWire::Match {
1928 evidence: evidence.clone(),
1929 }
1930 .serialize(serializer),
1931 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1932 running: running.clone(),
1933 disk: disk.clone(),
1934 }
1935 .serialize(serializer),
1936 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1937 reason: reason.clone(),
1938 }
1939 .serialize(serializer),
1940 Self::Unknown { body, .. } => body.serialize(serializer),
1941 }
1942 }
1943}
1944
1945impl Serialize for ReloadPathAgreement {
1946 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1947 where
1948 S: Serializer,
1949 {
1950 match self {
1951 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1952 Self::Mismatch {
1953 configured,
1954 spawned_from,
1955 } => ReloadPathAgreementWire::Mismatch {
1956 configured: configured.clone(),
1957 spawned_from: spawned_from.clone(),
1958 }
1959 .serialize(serializer),
1960 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1961 reason: reason.clone(),
1962 }
1963 .serialize(serializer),
1964 Self::Unknown { body, .. } => body.serialize(serializer),
1965 }
1966 }
1967}
1968
1969impl Serialize for LaunchSpecAgreement {
1970 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1971 where
1972 S: Serializer,
1973 {
1974 match self {
1975 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1976 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1977 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1978 reason: reason.clone(),
1979 }
1980 .serialize(serializer),
1981 Self::Unknown { body, .. } => body.serialize(serializer),
1982 }
1983 }
1984}
1985
1986impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1987 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1988 where
1989 D: Deserializer<'de>,
1990 {
1991 let (tag, body) = read_tagged(deserializer, "status")?;
1992 match tag.as_str() {
1993 "match" => Ok(Self::Match),
1994 "mismatch" => Ok(Self::Mismatch),
1995 "unavailable" => match serde_json::from_value(body.into_value())
1996 .map_err(D::Error::custom)?
1997 {
1998 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1999 _ => unreachable!(),
2000 },
2001 _ => Ok(Self::Unknown { tag, body }),
2002 }
2003 }
2004}
2005
2006impl<'de> Deserialize<'de> for ReloadPathAgreement {
2007 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2008 where
2009 D: Deserializer<'de>,
2010 {
2011 let (tag, body) = read_tagged(deserializer, "status")?;
2012 match tag.as_str() {
2013 "match" => Ok(Self::Match),
2014 "mismatch" => {
2015 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2016 ReloadPathAgreementWire::Mismatch {
2017 configured,
2018 spawned_from,
2019 } => Ok(Self::Mismatch {
2020 configured,
2021 spawned_from,
2022 }),
2023 _ => unreachable!(),
2024 }
2025 }
2026 "unavailable" => match serde_json::from_value(body.into_value())
2027 .map_err(D::Error::custom)?
2028 {
2029 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
2030 _ => unreachable!(),
2031 },
2032 _ => Ok(Self::Unknown { tag, body }),
2033 }
2034 }
2035}
2036
2037impl<'de> Deserialize<'de> for RunningImageAgreement {
2038 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2039 where
2040 D: serde::Deserializer<'de>,
2041 {
2042 let (tag, value) = read_tagged(deserializer, "status")?;
2043 match tag.as_str() {
2044 "match" => Ok(Self::Match {
2045 evidence: decode_running_image_evidence(
2046 ordered_field(&value, "evidence")
2047 .cloned()
2048 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
2049 )
2050 .map_err(D::Error::custom)?,
2051 }),
2052 "mismatch" => Ok(Self::Mismatch {
2053 running: decode_running_image_evidence(
2054 ordered_field(&value, "running")
2055 .cloned()
2056 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
2057 )
2058 .map_err(D::Error::custom)?,
2059 disk: decode_running_image_evidence(
2060 ordered_field(&value, "disk")
2061 .cloned()
2062 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
2063 )
2064 .map_err(D::Error::custom)?,
2065 }),
2066 "unavailable" => Ok(Self::Unavailable {
2067 reason: serde_json::from_value(
2068 ordered_field(&value, "reason")
2069 .cloned()
2070 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
2071 .into_value(),
2072 )
2073 .map_err(D::Error::custom)?,
2074 }),
2075 _ => Ok(Self::Unknown { tag, body: value }),
2076 }
2077 }
2078}
2079
2080impl Serialize for ChildResourceUsage {
2081 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2082 where
2083 S: Serializer,
2084 {
2085 match self {
2086 Self::Measured(reading) => {
2087 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
2088 }
2089 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
2090 reason: reason.clone(),
2091 }
2092 .serialize(serializer),
2093 Self::Unknown { body, .. } => body.serialize(serializer),
2094 }
2095 }
2096}
2097
2098impl<'de> Deserialize<'de> for ChildResourceUsage {
2099 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2100 where
2101 D: Deserializer<'de>,
2102 {
2103 let (tag, body) = read_tagged(deserializer, "status")?;
2104 match tag.as_str() {
2105 "measured" | "unavailable" => {
2106 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2107 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
2108 ChildResourceUsageWire::Unavailable { reason } => {
2109 Ok(Self::Unavailable { reason })
2110 }
2111 }
2112 }
2113 _ => Ok(Self::Unknown { tag, body }),
2114 }
2115 }
2116}
2117
2118impl Serialize for RunningImageEvidence {
2119 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2120 where
2121 S: Serializer,
2122 {
2123 match self {
2124 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
2125 digest: digest.clone(),
2126 }
2127 .serialize(serializer),
2128 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
2129 device: *device,
2130 inode: *inode,
2131 }
2132 .serialize(serializer),
2133 Self::WindowsSpawnFileId {
2134 volume_serial_number,
2135 file_id,
2136 } => RunningImageEvidenceWire::WindowsSpawnFileId {
2137 volume_serial_number: *volume_serial_number,
2138 file_id: *file_id,
2139 }
2140 .serialize(serializer),
2141 Self::Unknown { body, .. } => body.serialize(serializer),
2142 }
2143 }
2144}
2145
2146impl<'de> Deserialize<'de> for RunningImageEvidence {
2147 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2148 where
2149 D: serde::Deserializer<'de>,
2150 {
2151 let (tag, value) = read_tagged(deserializer, "method")?;
2152 match tag.as_str() {
2153 "linux_proc_sha256" => {
2154 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2155 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
2156 Ok(Self::LinuxProcSha256 { digest })
2157 }
2158 _ => unreachable!(),
2159 }
2160 }
2161 "macos_spawn_inode" => {
2162 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2163 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
2164 Ok(Self::MacosSpawnInode { device, inode })
2165 }
2166 _ => unreachable!(),
2167 }
2168 }
2169 "windows_spawn_file_id" => {
2170 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2171 RunningImageEvidenceWire::WindowsSpawnFileId {
2172 volume_serial_number,
2173 file_id,
2174 } => Ok(Self::WindowsSpawnFileId {
2175 volume_serial_number,
2176 file_id,
2177 }),
2178 _ => unreachable!(),
2179 }
2180 }
2181 _ => Ok(Self::Unknown { tag, body: value }),
2182 }
2183 }
2184}
2185
2186impl Serialize for SupervisorRouteConsumer {
2187 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2188 where
2189 S: Serializer,
2190 {
2191 match self {
2192 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
2193 module_id: module_id.clone(),
2194 }
2195 .serialize(serializer),
2196 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
2197 connection_id: *connection_id,
2198 }
2199 .serialize(serializer),
2200 Self::Unknown { body, .. } => body.serialize(serializer),
2201 }
2202 }
2203}
2204
2205impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
2206 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2207 where
2208 D: serde::Deserializer<'de>,
2209 {
2210 let (tag, value) = read_tagged(deserializer, "kind")?;
2211 match tag.as_str() {
2212 "reserved" => {
2213 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2214 SupervisorRouteConsumerWire::Reserved { module_id } => {
2215 Ok(Self::Reserved { module_id })
2216 }
2217 _ => unreachable!(),
2218 }
2219 }
2220 "direct" => {
2221 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2222 SupervisorRouteConsumerWire::Direct { connection_id } => {
2223 Ok(Self::Direct { connection_id })
2224 }
2225 _ => unreachable!(),
2226 }
2227 }
2228 _ => Ok(Self::Unknown { tag, body: value }),
2229 }
2230 }
2231}
2232
2233impl Serialize for StderrCaptureState {
2234 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2235 where
2236 S: Serializer,
2237 {
2238 match self {
2239 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
2240 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
2241 reason: reason.clone(),
2242 }
2243 .serialize(serializer),
2244 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
2245 reason: reason.clone(),
2246 }
2247 .serialize(serializer),
2248 Self::Unknown { body, .. } => body.serialize(serializer),
2249 }
2250 }
2251}
2252
2253impl<'de> Deserialize<'de> for StderrCaptureState {
2254 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2255 where
2256 D: serde::Deserializer<'de>,
2257 {
2258 let (tag, value) = read_tagged(deserializer, "state")?;
2259 match tag.as_str() {
2260 "captured" => {
2261 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2262 StderrCaptureStateWire::Captured => Ok(Self::Captured),
2263 _ => unreachable!(),
2264 }
2265 }
2266 "incomplete" => match serde_json::from_value(value.into_value())
2267 .map_err(D::Error::custom)?
2268 {
2269 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
2270 _ => unreachable!(),
2271 },
2272 "not_captured" => match serde_json::from_value(value.into_value())
2273 .map_err(D::Error::custom)?
2274 {
2275 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
2276 _ => unreachable!(),
2277 },
2278 _ => Ok(Self::Unknown { tag, body: value }),
2279 }
2280 }
2281}
2282
2283impl Serialize for StderrTailEntry {
2284 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2285 where
2286 S: Serializer,
2287 {
2288 match self {
2289 Self::Line {
2290 text,
2291 truncated,
2292 at_ms,
2293 } => StderrTailEntryWire::Line {
2294 text: text.clone(),
2295 truncated: *truncated,
2296 at_ms: *at_ms,
2297 }
2298 .serialize(serializer),
2299 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
2300 Self::Unknown { body, .. } => body.serialize(serializer),
2301 }
2302 }
2303}
2304
2305impl<'de> Deserialize<'de> for StderrTailEntry {
2306 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2307 where
2308 D: serde::Deserializer<'de>,
2309 {
2310 let (tag, value) = read_tagged(deserializer, "kind")?;
2311 match tag.as_str() {
2312 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2313 StderrTailEntryWire::Line {
2314 text,
2315 truncated,
2316 at_ms,
2317 } => Ok(Self::Line {
2318 text,
2319 truncated,
2320 at_ms,
2321 }),
2322 _ => unreachable!(),
2323 },
2324 "process_start" => {
2325 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2326 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
2327 _ => unreachable!(),
2328 }
2329 }
2330 _ => Ok(Self::Unknown { tag, body: value }),
2331 }
2332 }
2333}
2334
2335fn is_zero_u64(value: &u64) -> bool {
2336 *value == 0
2337}
2338
2339fn default_true() -> bool {
2340 true
2341}
2342
2343#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2345pub struct TerminalHistory {
2346 pub daemon_started_at_ms: u64,
2348 pub entries: Vec<TerminalEntry>,
2349 #[serde(default, skip_serializing_if = "is_zero_u64")]
2352 pub dropped: u64,
2353 #[serde(default, skip_serializing_if = "is_zero_u64")]
2356 pub journal_skipped_lines: u64,
2357 #[serde(default, skip_serializing_if = "is_zero_u64")]
2359 pub journal_read_errors: u64,
2360 #[serde(default, skip_serializing_if = "is_zero_u64")]
2362 pub journal_write_failures: u64,
2363}
2364
2365#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2367pub struct TerminalEntry {
2368 #[serde(default, skip_serializing_if = "Option::is_none")]
2371 pub daemon_incarnation: Option<String>,
2372 #[serde(default, skip_serializing_if = "Option::is_none")]
2373 pub exit_code: Option<i32>,
2374 #[serde(default, skip_serializing_if = "Option::is_none")]
2375 pub exit_signal: Option<i32>,
2376 pub at_ms: u64,
2377 pub disposition: TerminalDisposition,
2378 #[serde(default, skip_serializing_if = "Option::is_none")]
2382 pub exit_kind: Option<TerminalExitKind>,
2383 #[serde(default, skip_serializing_if = "Option::is_none")]
2390 pub disposition_detail: Option<String>,
2391}
2392
2393#[derive(Debug, Clone, PartialEq, Eq)]
2398pub enum TerminalExitKind {
2399 Clean,
2400 Crash,
2401 DeliberateSeverance,
2402 Unknown(String),
2403}
2404
2405impl TerminalExitKind {
2406 fn wire_name(&self) -> &str {
2407 match self {
2408 Self::Clean => "clean",
2409 Self::Crash => "crash",
2410 Self::DeliberateSeverance => "deliberate_severance",
2411 Self::Unknown(value) => value,
2412 }
2413 }
2414}
2415
2416impl Serialize for TerminalExitKind {
2417 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2418 where
2419 S: serde::Serializer,
2420 {
2421 serializer.serialize_str(self.wire_name())
2422 }
2423}
2424
2425impl<'de> Deserialize<'de> for TerminalExitKind {
2426 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2427 where
2428 D: serde::Deserializer<'de>,
2429 {
2430 let value = String::deserialize(deserializer)?;
2431 Ok(match value.as_str() {
2432 "clean" => Self::Clean,
2433 "crash" => Self::Crash,
2434 "deliberate_severance" => Self::DeliberateSeverance,
2435 _ => Self::Unknown(value),
2436 })
2437 }
2438}
2439
2440open_string_enum! {
2441 TerminalDisposition {
2443 Stopped => "stopped",
2444 Disabled => "disabled",
2445 Failed => "failed",
2446 Restarting => "restarting",
2447 DaemonShutdown => "daemon_shutdown",
2452 }
2453}
2454
2455#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2456#[serde(rename_all = "snake_case")]
2457pub enum PollKind {
2458 Status,
2459 Liveness,
2460}
2461
2462#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2474#[non_exhaustive]
2475pub struct CatalogEntry {
2476 pub module_id: String,
2477 #[serde(default, skip_serializing_if = "Option::is_none")]
2479 pub display_name: Option<String>,
2480 #[serde(default = "default_true")]
2491 pub ready: bool,
2492 #[serde(default, skip_serializing_if = "Option::is_none")]
2496 pub not_ready: Option<NotReadyReason>,
2497 #[serde(default, skip_serializing_if = "Option::is_none")]
2518 pub module_version: Option<String>,
2519 #[serde(default, skip_serializing_if = "Option::is_none")]
2522 pub provenance: Option<ManifestProvenance>,
2523 pub roles: Vec<ProviderRole>,
2524 pub control_ops: Vec<String>,
2525 #[serde(default, skip_serializing_if = "Option::is_none")]
2530 pub capabilities: Option<CapabilityDeclarations>,
2531 #[serde(default, skip_serializing_if = "Option::is_none")]
2534 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2535 #[serde(default, skip_serializing_if = "Option::is_none")]
2539 pub events: Option<Vec<EventDeclaration>>,
2540 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2543 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2544 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2547 pub operation_payload: BTreeMap<String, OperationPayload>,
2548 #[serde(default, skip_serializing_if = "Option::is_none")]
2554 pub flow_operations: Option<Vec<String>>,
2555 #[serde(default, skip_serializing_if = "Option::is_none")]
2557 pub operation_deferral: Option<BTreeMap<String, bool>>,
2558 #[serde(default, skip_serializing_if = "Option::is_none")]
2564 pub confirm_operations: Option<Vec<String>>,
2565 #[serde(default, skip_serializing_if = "Option::is_none")]
2568 pub rich_ui: Option<RichUiDescriptor>,
2569 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2572 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2573 #[serde(default, skip_serializing_if = "is_false")]
2578 pub nonce_verified: bool,
2579 #[serde(default, skip_serializing_if = "Option::is_none")]
2582 pub incarnation: Option<String>,
2583 #[serde(
2584 default,
2585 skip_serializing_if = "Option::is_none",
2586 deserialize_with = "deserialize_optional_attestation_integer"
2587 )]
2588 pub spawn: Option<u64>,
2589 #[serde(default, skip_serializing_if = "Option::is_none")]
2590 pub first_party: Option<bool>,
2591 #[serde(default, skip_serializing_if = "Option::is_none")]
2592 pub origin: Option<CatalogOrigin>,
2593 #[serde(default, skip_serializing_if = "Option::is_none")]
2594 pub requested_declarations_digest: Option<String>,
2595 #[serde(default, skip_serializing_if = "Option::is_none")]
2596 pub approved_declarations_digest: Option<String>,
2597 #[serde(default, skip_serializing_if = "Option::is_none")]
2600 pub approved_declarations: Option<ProviderDeclarations>,
2601 #[serde(default, skip_serializing_if = "Option::is_none")]
2602 pub requested_declarations: Option<ProviderDeclarations>,
2603}
2604
2605impl CatalogEntry {
2606 #[must_use]
2608 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2609 self.display_name = display_name;
2610 self
2611 }
2612
2613 #[must_use]
2615 pub fn new(
2616 module_id: impl Into<String>,
2617 roles: Vec<ProviderRole>,
2618 control_ops: Vec<String>,
2619 ) -> Self {
2620 Self {
2621 module_id: module_id.into(),
2622 ready: default_true(),
2623 display_name: None,
2624 not_ready: None,
2625 module_version: None,
2626 provenance: None,
2627 roles,
2628 control_ops,
2629 capabilities: None,
2630 self_signals: None,
2631 events: None,
2632 operation_delivery: BTreeMap::new(),
2633 operation_payload: BTreeMap::new(),
2634 flow_operations: None,
2635 operation_deferral: None,
2636 confirm_operations: None,
2637 rich_ui: None,
2638 role_declarations: BTreeMap::new(),
2639 nonce_verified: false,
2640 incarnation: None,
2641 spawn: None,
2642 first_party: None,
2643 origin: None,
2644 requested_declarations_digest: None,
2645 approved_declarations_digest: None,
2646 approved_declarations: None,
2647 requested_declarations: None,
2648 }
2649 }
2650
2651 #[must_use]
2653 pub fn with_operation_payload(
2654 mut self,
2655 operation_payload: BTreeMap<String, OperationPayload>,
2656 ) -> Self {
2657 self.operation_payload = operation_payload;
2658 self
2659 }
2660
2661 #[must_use]
2664 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2665 self.flow_operations = flow_operations;
2666 self
2667 }
2668
2669 #[must_use]
2671 pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
2672 self.operation_deferral = operations;
2673 self
2674 }
2675
2676 #[must_use]
2679 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2680 self.confirm_operations = confirm_operations;
2681 self
2682 }
2683
2684 #[must_use]
2686 pub fn with_ready(mut self, ready: bool) -> Self {
2687 self.ready = ready;
2688 self
2689 }
2690
2691 #[must_use]
2693 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2694 self.not_ready = not_ready;
2695 self
2696 }
2697
2698 #[must_use]
2700 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2701 self.module_version = module_version;
2702 self
2703 }
2704
2705 #[must_use]
2707 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2708 self.provenance = provenance;
2709 self
2710 }
2711
2712 #[must_use]
2714 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2715 self.capabilities = capabilities;
2716 self
2717 }
2718
2719 #[must_use]
2721 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2722 self.self_signals = self_signals;
2723 self
2724 }
2725
2726 #[must_use]
2728 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2729 self.events = events;
2730 self
2731 }
2732
2733 #[must_use]
2736 pub fn with_operation_delivery(
2737 mut self,
2738 operation_delivery: BTreeMap<String, OperationDelivery>,
2739 ) -> Self {
2740 self.operation_delivery = operation_delivery;
2741 self
2742 }
2743
2744 #[must_use]
2746 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2747 self.rich_ui = rich_ui;
2748 self
2749 }
2750
2751 #[must_use]
2753 pub fn with_role_declarations(
2754 mut self,
2755 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2756 ) -> Self {
2757 self.role_declarations = role_declarations;
2758 self
2759 }
2760
2761 #[must_use]
2763 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2764 self.nonce_verified = nonce_verified;
2765 self
2766 }
2767}
2768
2769fn is_false(value: &bool) -> bool {
2770 !value
2771}
2772
2773#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2775pub struct NotReadyReason {
2776 pub reason: String,
2781 #[serde(default, skip_serializing_if = "Option::is_none")]
2784 pub capability: Option<String>,
2785}
2786
2787impl NotReadyReason {
2788 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2789 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2790}
2791
2792#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2793pub struct CapabilityRequirementStatus {
2794 pub consumer: String,
2795 pub capability: String,
2796 pub need: String,
2797 pub verdict: String,
2798 pub episode_seq: u64,
2799 pub config_satisfiable: bool,
2800 pub runtime_available: bool,
2801 pub detail: String,
2802}
2803
2804#[non_exhaustive]
2809#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2810#[serde(rename_all = "snake_case")]
2811pub enum PendingModuleApply {
2812 NextSupervision,
2813 WithNextLaunchOrHealthChange,
2814 DaemonRestart,
2815 ConfigGate,
2816 #[serde(other)]
2817 Other,
2818}
2819
2820#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2822pub struct SupervisorPendingField {
2823 pub field: String,
2824 pub applies: PendingModuleApply,
2825 #[serde(default, skip_serializing_if = "Option::is_none")]
2826 pub value: Option<serde_json::Value>,
2827}
2828
2829#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2830pub struct SupervisorPendingModule {
2831 pub module_id: String,
2832 pub fields: Vec<SupervisorPendingField>,
2833}
2834
2835#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2836pub struct SupervisorRescanResult {
2837 pub added: Vec<String>,
2838 pub removed: Vec<String>,
2839 pub changed_pending_reload: Vec<String>,
2840 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2842 pub changed_pending: Vec<SupervisorPendingModule>,
2843 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2856 pub enabled_changes: Vec<String>,
2857 pub unchanged: u32,
2858 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2866 pub preview: bool,
2867 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2885 pub restart_required: Vec<String>,
2886 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2890 pub capability_warnings: Vec<String>,
2891 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2898 pub module_actions: Vec<RescanModuleAction>,
2899 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2903 pub earlier_pending: Vec<String>,
2904 #[serde(default, skip_serializing_if = "Option::is_none")]
2907 pub expect: Option<RescanExpect>,
2908}
2909
2910#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2926#[serde(rename_all = "snake_case")]
2927pub enum ModuleProtocol {
2928 #[default]
2932 Subc,
2933 None,
2942}
2943
2944#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2956#[non_exhaustive]
2957pub struct SupervisorEntry {
2958 #[serde(default, skip_serializing_if = "Option::is_none")]
2960 pub script: Option<ScriptModuleStatus>,
2961 #[serde(default, skip_serializing_if = "Option::is_none")]
2964 pub waiting_for_previous_pid: Option<u32>,
2965 #[serde(default, skip_serializing_if = "Option::is_none")]
2968 pub waiting_for_previous_detail: Option<String>,
2969 pub module_id: String,
2970 pub state: String,
2971 #[serde(default, skip_serializing_if = "Option::is_none")]
2973 pub accepting_drain: Option<bool>,
2974 #[serde(default, skip_serializing_if = "Option::is_none")]
2978 pub admission_refused: Option<String>,
2979 #[serde(default, skip_serializing_if = "Option::is_none")]
2983 pub next_retry_at_ms: Option<u64>,
2984 pub enabled: bool,
2985 #[serde(default, skip_serializing_if = "Option::is_none")]
2988 pub configured_enabled: Option<bool>,
2989 pub live: bool,
2999 #[serde(default)]
3003 pub protocol: ModuleProtocol,
3004 #[serde(default, skip_serializing_if = "Option::is_none")]
3007 pub launch_nonce_env: Option<bool>,
3008 #[serde(default, skip_serializing_if = "Option::is_none")]
3014 pub launch_nonce_source: Option<String>,
3015 pub health: SupervisorHealthStatus,
3016 #[serde(default, skip_serializing_if = "Option::is_none")]
3019 pub pending_reload: Option<PendingReloadVerdict>,
3020 #[serde(default)]
3026 pub last_probe_ms: Option<u64>,
3027 #[serde(default, skip_serializing_if = "Option::is_none")]
3031 pub last_exit_code: Option<i32>,
3032 #[serde(default, skip_serializing_if = "Option::is_none")]
3036 pub last_exit_signal: Option<i32>,
3037 #[serde(default, skip_serializing_if = "Option::is_none")]
3041 pub last_exit_ms: Option<u64>,
3042 #[serde(default, skip_serializing_if = "Option::is_none")]
3045 pub last_exit_kind: Option<TerminalExitKind>,
3046 #[serde(default, skip_serializing_if = "Option::is_none")]
3063 pub restart_count: Option<u32>,
3064 #[serde(default, skip_serializing_if = "Option::is_none")]
3067 pub max_restarts: Option<u32>,
3068 #[serde(default, skip_serializing_if = "Option::is_none")]
3071 pub lifetime_restarts: Option<u32>,
3072 #[serde(default, skip_serializing_if = "Option::is_none")]
3076 pub spawn_generation: Option<u64>,
3077 #[serde(default, skip_serializing_if = "Option::is_none")]
3087 pub restart_window_secs: Option<u64>,
3088 #[serde(default, skip_serializing_if = "Option::is_none")]
3092 pub drain_timeout_ms: Option<u64>,
3093 #[serde(default, skip_serializing_if = "Option::is_none")]
3096 pub restart_backoff_ms: Option<u64>,
3097 #[serde(default, skip_serializing_if = "Option::is_none")]
3100 pub restart_max_backoff_ms: Option<u64>,
3101 #[serde(default, skip_serializing_if = "Option::is_none")]
3114 pub resources: Option<ChildResourceUsage>,
3115 #[serde(default, skip_serializing_if = "Option::is_none")]
3117 pub tree: Option<TreeReading>,
3118 #[serde(default, skip_serializing_if = "Option::is_none")]
3124 pub tree_unavailable: Option<String>,
3125 #[serde(default, skip_serializing_if = "Option::is_none")]
3127 pub cpu_last_hour: Option<CpuLastHour>,
3128 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3130 pub pending: Vec<SupervisorPendingField>,
3131}
3132
3133impl SupervisorEntry {
3134 #[must_use]
3135 pub fn with_script(mut self, script: Option<ScriptModuleStatus>) -> Self {
3136 self.script = script;
3137 self
3138 }
3139 #[must_use]
3141 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3142 self.next_retry_at_ms = next_retry_at_ms;
3143 self
3144 }
3145
3146 #[must_use]
3148 pub fn new(
3149 module_id: impl Into<String>,
3150 state: impl Into<String>,
3151 enabled: bool,
3152 live: bool,
3153 health: SupervisorHealthStatus,
3154 ) -> Self {
3155 Self {
3156 module_id: module_id.into(),
3157 script: None,
3158 state: state.into(),
3159 admission_refused: None,
3160 next_retry_at_ms: None,
3161 waiting_for_previous_pid: None,
3162 waiting_for_previous_detail: None,
3163 accepting_drain: None,
3164 enabled,
3165 configured_enabled: None,
3166 live,
3167 protocol: ModuleProtocol::default(),
3168 launch_nonce_env: None,
3169 launch_nonce_source: None,
3170 health,
3171 pending_reload: None,
3172 last_probe_ms: None,
3173 last_exit_code: None,
3174 last_exit_signal: None,
3175 last_exit_ms: None,
3176 last_exit_kind: None,
3177 restart_count: None,
3178 max_restarts: None,
3179 lifetime_restarts: None,
3180 spawn_generation: None,
3181 restart_window_secs: None,
3182 drain_timeout_ms: None,
3183 restart_backoff_ms: None,
3184 restart_max_backoff_ms: None,
3185 resources: None,
3186 tree: None,
3187 tree_unavailable: None,
3188 cpu_last_hour: None,
3189 pending: Vec::new(),
3190 }
3191 }
3192
3193 #[must_use]
3195 pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3196 self.admission_refused = reason;
3197 self
3198 }
3199
3200 #[must_use]
3202 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3203 self.protocol = protocol;
3204 self
3205 }
3206
3207 #[must_use]
3209 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3210 self.configured_enabled = configured_enabled;
3211 self
3212 }
3213
3214 #[must_use]
3216 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3217 self.launch_nonce_env = launch_nonce_env;
3218 self
3219 }
3220
3221 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3222 self.launch_nonce_source = source;
3223 self
3224 }
3225
3226 #[must_use]
3227 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3228 self.waiting_for_previous_pid = pid;
3229 self
3230 }
3231
3232 #[must_use]
3233 pub fn with_waiting_for_previous_detail(mut self, detail: Option<String>) -> Self {
3234 self.waiting_for_previous_detail = detail;
3235 self
3236 }
3237
3238 #[must_use]
3240 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3241 self.pending_reload = pending_reload;
3242 self
3243 }
3244
3245 #[must_use]
3247 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3248 self.last_probe_ms = last_probe_ms;
3249 self
3250 }
3251
3252 #[must_use]
3254 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3255 self.last_exit_code = last_exit_code;
3256 self
3257 }
3258
3259 #[must_use]
3261 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3262 self.last_exit_signal = last_exit_signal;
3263 self
3264 }
3265
3266 #[must_use]
3268 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3269 self.last_exit_ms = last_exit_ms;
3270 self
3271 }
3272
3273 #[must_use]
3275 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3276 self.last_exit_kind = last_exit_kind;
3277 self
3278 }
3279
3280 #[must_use]
3282 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3283 self.restart_count = restart_count;
3284 self
3285 }
3286
3287 #[must_use]
3289 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3290 self.max_restarts = max_restarts;
3291 self
3292 }
3293
3294 #[must_use]
3296 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3297 self.lifetime_restarts = lifetime_restarts;
3298 self
3299 }
3300
3301 #[must_use]
3303 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3304 self.spawn_generation = spawn_generation;
3305 self
3306 }
3307
3308 #[must_use]
3310 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3311 self.restart_window_secs = restart_window_secs;
3312 self
3313 }
3314
3315 #[must_use]
3317 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3318 self.drain_timeout_ms = drain_timeout_ms;
3319 self
3320 }
3321
3322 #[must_use]
3324 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3325 self.restart_backoff_ms = restart_backoff_ms;
3326 self
3327 }
3328
3329 #[must_use]
3331 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3332 self.restart_max_backoff_ms = restart_max_backoff_ms;
3333 self
3334 }
3335
3336 #[must_use]
3338 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3339 self.resources = resources;
3340 self
3341 }
3342
3343 #[must_use]
3345 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3346 self.tree = tree;
3347 self
3348 }
3349
3350 #[must_use]
3352 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3353 self.tree_unavailable = reason;
3354 self
3355 }
3356}
3357
3358#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3360pub struct ScriptModuleStatus {
3361 pub runtime: String,
3362 pub bun_version: Option<String>,
3363 pub path: PathBuf,
3364 pub sha256: Option<String>,
3365 pub size: Option<u64>,
3366 pub needs_review: bool,
3367}
3368
3369#[cfg(test)]
3370mod script_status_tests {
3371 use super::*;
3372
3373 #[test]
3374 fn script_status_roundtrips_and_old_supervisor_entries_remain_readable() {
3375 let old = SupervisorEntry::new(
3376 "example",
3377 "running",
3378 true,
3379 true,
3380 SupervisorHealthStatus::Unknown,
3381 );
3382 let value = serde_json::to_value(&old).unwrap();
3383 assert!(value.get("script").is_none());
3384 assert!(serde_json::from_value::<SupervisorEntry>(value)
3385 .unwrap()
3386 .script
3387 .is_none());
3388 let current = old.with_script(Some(ScriptModuleStatus {
3389 runtime: "bun".into(),
3390 bun_version: None,
3391 path: "bundle.js".into(),
3392 sha256: Some("ab".repeat(32)),
3393 size: Some(3),
3394 needs_review: true,
3395 }));
3396 let decoded: SupervisorEntry =
3397 serde_json::from_slice(&serde_json::to_vec(¤t).unwrap()).unwrap();
3398 assert_eq!(decoded, current);
3399 }
3400}
3401
3402#[derive(Debug, Clone, PartialEq)]
3405pub enum ChildResourceUsage {
3406 Measured(ChildResourceReading),
3407 Unavailable {
3408 reason: ChildResourceUnavailableReason,
3409 },
3410 Unknown {
3413 tag: String,
3414 body: OrderedJsonObject,
3415 },
3416}
3417
3418#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3421#[non_exhaustive]
3422pub struct ChildResourceReading {
3423 pub memory_bytes: u64,
3426 pub memory_kind: ChildMemoryKind,
3427 #[serde(default, skip_serializing_if = "Option::is_none")]
3430 pub swap_bytes: Option<u64>,
3431 pub cpu_user_ms: u64,
3435 pub cpu_system_ms: u64,
3438}
3439
3440impl ChildResourceReading {
3441 #[must_use]
3443 pub fn new(
3444 memory_bytes: u64,
3445 memory_kind: ChildMemoryKind,
3446 cpu_user_ms: u64,
3447 cpu_system_ms: u64,
3448 ) -> Self {
3449 Self {
3450 memory_bytes,
3451 memory_kind,
3452 cpu_user_ms,
3453 cpu_system_ms,
3454 swap_bytes: None,
3455 }
3456 }
3457
3458 #[must_use]
3460 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3461 self.swap_bytes = swap_bytes;
3462 self
3463 }
3464}
3465
3466open_string_enum! {
3467 ChildMemoryKind {
3469 PhysFootprint => "phys_footprint",
3473 ResidentSet => "resident_set",
3476 WindowsWorkingSet => "windows_working_set",
3479 }
3480}
3481
3482open_string_enum! {
3483 ChildResourceUnavailableReason {
3485 NotRunning => "not_running",
3487 UnsupportedPlatform => "unsupported_platform",
3489 Unreadable => "unreadable",
3492 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3495 }
3496}
3497
3498#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3499#[serde(rename_all = "snake_case")]
3500pub enum SupervisorHealthStatus {
3501 Ok,
3502 Degraded,
3503 Failing,
3504 Unresponsive,
3505 Unknown,
3506}
3507
3508#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3509pub struct SupervisorHealthEntry {
3510 pub module_id: String,
3511 pub status: SupervisorHealthStatus,
3512 #[serde(default, skip_serializing_if = "Option::is_none")]
3518 pub detail: Option<String>,
3519 #[serde(default, skip_serializing_if = "Option::is_none")]
3524 pub metrics: Option<serde_json::Value>,
3525 pub consecutive_failures: u32,
3526 #[serde(default)]
3529 pub late_answer_count: u64,
3530 #[serde(default, skip_serializing_if = "Option::is_none")]
3532 pub last_late_answer_latency_ms: Option<u64>,
3533 #[serde(default)]
3538 pub last_action: Option<String>,
3539 #[serde(default)]
3542 pub last_action_ms: Option<u64>,
3543 #[serde(default, skip_serializing_if = "Option::is_none")]
3556 pub last_probe_ms: Option<u64>,
3557}
3558
3559#[cfg(test)]
3560mod tests {
3561 #[test]
3562 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3563 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3564 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3565 assert_eq!(decoded.configured_enabled, None);
3566 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3567 }
3568
3569 #[test]
3570 fn configured_enabled_values_round_trip_in_list() {
3571 for enabled in [false, true] {
3572 let entry = SupervisorEntry::new(
3573 "provider",
3574 "running",
3575 true,
3576 true,
3577 SupervisorHealthStatus::Unknown,
3578 )
3579 .with_configured_enabled(Some(enabled));
3580 let entry_json = serde_json::to_value(&entry).unwrap();
3581 assert_eq!(entry_json["configured_enabled"], enabled);
3582 assert_eq!(
3583 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3584 entry
3585 );
3586 }
3587 }
3588
3589 #[test]
3590 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3591 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3592 volume_serial_number: u64::MAX,
3593 file_id: [
3594 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3595 ],
3596 };
3597 let agreement = super::RunningImageAgreement::Match { evidence };
3598 let encoded = serde_json::to_string(&agreement).unwrap();
3599 assert!(encoded.contains("windows_spawn_file_id"));
3600 assert_eq!(
3601 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3602 agreement
3603 );
3604 }
3605
3606 #[test]
3607 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3608 assert_eq!(
3609 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3610 device: 7,
3611 inode: 11
3612 })
3613 .unwrap(),
3614 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3615 );
3616 assert_eq!(
3617 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3618 digest: "abc".to_owned()
3619 })
3620 .unwrap(),
3621 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3622 );
3623 }
3624 use super::*;
3625 use subc_protocol::{BindIdentity, RouteTarget};
3626
3627 #[test]
3628 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3629 let entry = TerminalEntry {
3630 daemon_incarnation: Some("daemon-before-restart".into()),
3631 exit_code: Some(1),
3632 exit_signal: None,
3633 at_ms: 1_700_000_000_123,
3634 disposition: TerminalDisposition::Restarting,
3635 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3636 disposition_detail: None,
3637 };
3638 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3639 assert_eq!(
3640 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3641 ["exit_kind"],
3642 "deliberate_severance"
3643 );
3644
3645 #[derive(serde::Deserialize)]
3646 struct LegacyTerminalEntry {
3647 exit_code: Option<i32>,
3648 exit_signal: Option<i32>,
3649 at_ms: u64,
3650 disposition: TerminalDisposition,
3651 }
3652
3653 let decoded: LegacyTerminalEntry =
3654 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3655 assert_eq!(decoded.exit_code, Some(1));
3656 assert_eq!(decoded.exit_signal, None);
3657 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3658 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3659
3660 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3661 let future: TerminalEntry =
3662 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3663 assert_eq!(
3664 future.exit_kind,
3665 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3666 );
3667 }
3668
3669 #[test]
3670 fn terminal_incarnation_is_optional_for_older_daemons() {
3671 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3672 "at_ms": 123,
3673 "disposition": "stopped"
3674 }))
3675 .unwrap();
3676 let encoded = serde_json::to_value(&entry).unwrap();
3677 assert_eq!(
3678 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3679 (None, None)
3680 );
3681 }
3682
3683 #[test]
3684 fn route_poll_uses_kind_field() {
3685 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3686 route_channel: 7,
3687 route_epoch: 11,
3688 kind: PollKind::Status,
3689 })
3690 .unwrap();
3691
3692 assert_eq!(body["op"], "route.poll");
3693 assert_eq!(body["route_epoch"], 11);
3694 assert_eq!(body["kind"], "status");
3695 assert!(body.get("op").is_some());
3696 }
3697
3698 #[test]
3699 fn route_open_is_internally_tagged() {
3700 let request = ClientControlRequest::RouteOpen {
3701 busy_refusals: None,
3702 target: RouteTarget::ToolProvider {
3703 module_id: "aft".to_string(),
3704 },
3705 identity: BindIdentity::new("opencode", "session-1"),
3706 consumer_identity: None,
3707 consumer_capabilities: None,
3708 role_versions: None,
3709 admission_facts: None,
3710 scope: None,
3711 };
3712
3713 let body = serde_json::to_value(request).unwrap();
3714 assert_eq!(body["op"], "route.open");
3715 assert_eq!(body["target"]["kind"], "tool_provider");
3716 assert!(body.get("consumer_identity").is_none());
3717 assert!(body.get("consumer_capabilities").is_none());
3718 assert!(body.get("role_versions").is_none());
3719 }
3720
3721 #[test]
3722 fn route_open_without_optional_fields_still_decodes() {
3723 let body = serde_json::json!({
3724 "op": "route.open",
3725 "target": { "kind": "tool_provider", "module_id": "aft" },
3726 "identity": {
3727 "project_root": "/tmp/project",
3728 "harness": "opencode",
3729 "session": "session-1"
3730 }
3731 });
3732
3733 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3734 let ClientControlRequest::RouteOpen {
3735 consumer_identity,
3736 consumer_capabilities,
3737 role_versions,
3738 admission_facts,
3739 ..
3740 } = decoded
3741 else {
3742 panic!("decoded wrong request variant");
3743 };
3744 assert_eq!(consumer_identity, None);
3745 assert_eq!(consumer_capabilities, None);
3746 assert_eq!(role_versions, None);
3747 assert_eq!(admission_facts, None);
3748 }
3749
3750 #[test]
3751 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3752 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3753 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3754 match decoded {
3755 ClientControlPush::RouteClosed {
3756 excluded_subscriptions,
3757 terminal,
3758 ..
3759 } => {
3760 assert_eq!(excluded_subscriptions, 0);
3761 assert_eq!(terminal, None);
3762 }
3763 other => panic!("unexpected push: {other:?}"),
3764 }
3765 assert!(!serde_json::to_string(&decoded)
3766 .unwrap()
3767 .contains("terminal"));
3768 }
3769
3770 #[test]
3771 fn old_route_closed_decoder_ignores_new_terminal_field() {
3772 #[derive(serde::Deserialize)]
3773 #[serde(tag = "op")]
3774 enum LegacyClientControlPush {
3775 #[serde(rename = "route.closed")]
3776 RouteClosed {
3777 module_id: String,
3778 reason: RouteCloseReason,
3779 drained: bool,
3780 abandoned: u32,
3781 },
3782 }
3783
3784 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3785 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3786 match decoded {
3787 LegacyClientControlPush::RouteClosed {
3788 module_id,
3789 reason,
3790 drained,
3791 abandoned,
3792 } => {
3793 assert_eq!(module_id, "aft-tools");
3794 assert_eq!(reason, RouteCloseReason::Crash);
3795 assert!(!drained);
3796 assert_eq!(abandoned, 0);
3797 }
3798 }
3799 }
3800
3801 #[test]
3802 fn supervisor_routes_is_a_control_plane_request() {
3803 let body = serde_json::json!({
3804 "op": "supervisor.routes",
3805 "module_id": "aft"
3806 });
3807
3808 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3809 assert_eq!(serde_json::to_value(request).unwrap(), body);
3810 }
3811
3812 #[test]
3813 fn diagnostic_string_enums_retain_unknown_wire_values() {
3814 let reason: RunningImageUnavailableReason =
3815 serde_json::from_str("\"future_reason\"").unwrap();
3816 let disposition: TerminalDisposition =
3817 serde_json::from_str("\"future_disposition\"").unwrap();
3818
3819 assert_eq!(
3820 reason,
3821 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3822 );
3823 assert_eq!(
3824 disposition,
3825 TerminalDisposition::Unknown("future_disposition".to_string())
3826 );
3827 }
3828
3829 #[test]
3830 fn diagnostic_string_enums_preserve_existing_wire_names() {
3831 let names = [
3832 (RunningImageUnavailableReason::NotRunning, "not_running"),
3833 (
3834 RunningImageUnavailableReason::UnsupportedPlatform,
3835 "unsupported_platform",
3836 ),
3837 (
3838 RunningImageUnavailableReason::RunningExecutableUnreadable,
3839 "running_executable_unreadable",
3840 ),
3841 (
3842 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3843 "running_executable_permission_denied",
3844 ),
3845 (
3846 RunningImageUnavailableReason::ProcessHidden,
3847 "process_hidden",
3848 ),
3849 (
3850 RunningImageUnavailableReason::SpawnedPathUnreadable,
3851 "spawned_path_unreadable",
3852 ),
3853 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3854 (
3855 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3856 "process_identity_unconfirmed",
3857 ),
3858 ];
3859 for (value, expected) in names {
3860 let wire = serde_json::to_string(&value).unwrap();
3861 assert_eq!(wire, format!("\"{expected}\""));
3862 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3863 assert_eq!(decoded, value);
3864 }
3865
3866 for (value, expected) in [
3867 (TerminalDisposition::Stopped, "stopped"),
3868 (TerminalDisposition::Disabled, "disabled"),
3869 (TerminalDisposition::Failed, "failed"),
3870 (TerminalDisposition::Restarting, "restarting"),
3871 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3872 ] {
3873 let wire = serde_json::to_string(&value).unwrap();
3874 assert_eq!(wire, format!("\"{expected}\""));
3875 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3876 assert_eq!(decoded, value);
3877 }
3878 }
3879
3880 #[test]
3881 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3882 let entry = SupervisorEntry::new(
3883 "waiting-module",
3884 "starting",
3885 true,
3886 false,
3887 SupervisorHealthStatus::Unknown,
3888 );
3889 let old_wire = serde_json::to_value(&entry).unwrap();
3890 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3891 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3892 assert_eq!(decoded.waiting_for_previous_pid, None);
3893 let entry = entry.with_waiting_for_previous_pid(Some(42));
3894 let wire = serde_json::to_value(&entry).unwrap();
3895 assert_eq!(wire["waiting_for_previous_pid"], 42);
3896 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3897 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3898 }
3899
3900 #[test]
3901 fn supervisor_waiting_previous_detail_is_optional_and_round_trips() {
3902 let entry = SupervisorEntry::new(
3903 "worker",
3904 "starting",
3905 true,
3906 false,
3907 SupervisorHealthStatus::Unknown,
3908 )
3909 .with_waiting_for_previous_pid(Some(41));
3910 let old_wire = serde_json::to_value(&entry).unwrap();
3911 assert!(old_wire.get("waiting_for_previous_detail").is_none());
3912 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3913 assert_eq!(decoded.waiting_for_previous_detail, None);
3914 let detail = "waiting: container survivors (pids [42])";
3915 let wire =
3916 serde_json::to_value(entry.with_waiting_for_previous_detail(Some(detail.into())))
3917 .unwrap();
3918 assert_eq!(wire["waiting_for_previous_pid"], 41);
3919 assert_eq!(wire["waiting_for_previous_detail"], detail);
3920 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3921 assert_eq!(decoded.waiting_for_previous_detail.as_deref(), Some(detail));
3922 }
3923
3924 #[test]
3925 fn diagnostic_string_enums_reject_non_string_bodies() {
3926 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3927 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3928 }
3929
3930 #[test]
3931 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3932 let body = serde_json::json!({
3933 "op": "supervisor.provenance",
3934 "daemon": {
3935 "daemon_build": {},
3936 "daemon_observed": {
3937 "running_image": {
3938 "status": "unavailable",
3939 "reason": "not_running"
3940 }
3941 }
3942 },
3943 "modules": [
3944 {
3945 "module_id": "future",
3946 "module_declared": { "status": "unverifiable" },
3947 "daemon_observed": {
3948 "running_image": {
3949 "status": "unavailable",
3950 "reason": "future_reason"
3951 }
3952 }
3953 },
3954 {
3955 "module_id": "healthy-a",
3956 "module_declared": { "status": "unverifiable" },
3957 "daemon_observed": {
3958 "running_image": {
3959 "status": "match",
3960 "evidence": {
3961 "method": "linux_proc_sha256",
3962 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3963 }
3964 }
3965 }
3966 },
3967 {
3968 "module_id": "healthy-b",
3969 "module_declared": { "status": "unverifiable" },
3970 "daemon_observed": {
3971 "running_image": {
3972 "status": "unavailable",
3973 "reason": "unsupported_platform"
3974 }
3975 }
3976 }
3977 ]
3978 });
3979
3980 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3981 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3982 panic!("decoded wrong response variant");
3983 };
3984 assert_eq!(modules.len(), 3);
3985 assert_eq!(modules[0].module_id, "future");
3986 assert_eq!(
3987 modules[0].daemon_observed.running_image,
3988 RunningImageAgreement::Unavailable {
3989 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3990 }
3991 );
3992 assert_eq!(modules[1].module_id, "healthy-a");
3993 assert_eq!(modules[2].module_id, "healthy-b");
3994 }
3995
3996 #[test]
3997 fn tagged_unknown_values_retain_tag_and_body() {
3998 macro_rules! assert_unknown_round_trip {
3999 ($ty:ident, $field:literal, $value:expr) => {
4000 let value = $value;
4001 let wire = serde_json::to_string(&value).unwrap();
4002 let decoded: $ty = serde_json::from_str(&wire).unwrap();
4003 match decoded {
4004 $ty::Unknown { tag, body } => {
4005 assert_eq!(tag, value[$field].as_str().unwrap());
4006 assert_eq!(serde_json::to_value(&body).unwrap(), value);
4007 }
4008 _ => panic!("decoded known variant"),
4009 }
4010 };
4011 }
4012
4013 assert_unknown_round_trip!(
4014 ModuleDeclaredProvenance,
4015 "status",
4016 serde_json::json!({"status": "future", "build": {"version": 7}})
4017 );
4018 assert_unknown_round_trip!(
4019 RunningImageAgreement,
4020 "status",
4021 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
4022 );
4023 assert_unknown_round_trip!(
4024 RunningImageEvidence,
4025 "method",
4026 serde_json::json!({"method": "future", "digest": "abc"})
4027 );
4028 assert_unknown_round_trip!(
4029 SupervisorRouteConsumer,
4030 "kind",
4031 serde_json::json!({"kind": "future", "module_id": "m"})
4032 );
4033 assert_unknown_round_trip!(
4034 StderrCaptureState,
4035 "state",
4036 serde_json::json!({"state": "future", "reason": "because"})
4037 );
4038 assert_unknown_round_trip!(
4039 StderrTailEntry,
4040 "kind",
4041 serde_json::json!({"kind": "future", "text": "line"})
4042 );
4043 assert_unknown_round_trip!(
4044 ChildResourceUsage,
4045 "status",
4046 serde_json::json!({"status": "future", "memory_bytes": 1})
4047 );
4048 }
4049
4050 #[test]
4051 fn child_resource_usage_round_trips_both_known_states() {
4052 let measured = ChildResourceUsage::Measured(ChildResourceReading {
4053 memory_bytes: 0,
4054 memory_kind: ChildMemoryKind::ResidentSet,
4055 swap_bytes: Some(0),
4056 cpu_user_ms: 0,
4057 cpu_system_ms: 0,
4058 });
4059 let wire = serde_json::to_value(&measured).unwrap();
4060 assert_eq!(
4061 wire,
4062 serde_json::json!({
4063 "status": "measured",
4064 "memory_bytes": 0,
4065 "memory_kind": "resident_set",
4066 "swap_bytes": 0,
4067 "cpu_user_ms": 0,
4068 "cpu_system_ms": 0
4069 })
4070 );
4071 assert_eq!(
4072 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4073 measured
4074 );
4075
4076 let unavailable = ChildResourceUsage::Unavailable {
4077 reason: ChildResourceUnavailableReason::NotRunning,
4078 };
4079 let wire = serde_json::to_value(&unavailable).unwrap();
4080 assert_eq!(
4081 wire,
4082 serde_json::json!({"status": "unavailable", "reason": "not_running"})
4083 );
4084 assert_eq!(
4085 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4086 unavailable
4087 );
4088 }
4089
4090 #[test]
4091 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
4092 let stamped: StderrTailEntry = serde_json::from_str(
4096 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
4097 )
4098 .unwrap();
4099 assert_eq!(
4100 stamped,
4101 StderrTailEntry::Line {
4102 text: "boom".to_string(),
4103 truncated: true,
4104 at_ms: Some(1_789_801_440_685),
4105 }
4106 );
4107 let unstamped: StderrTailEntry =
4108 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
4109 assert_eq!(
4110 unstamped,
4111 StderrTailEntry::Line {
4112 text: "boom".to_string(),
4113 truncated: false,
4114 at_ms: None,
4115 }
4116 );
4117 assert_eq!(
4120 serde_json::to_string(&unstamped).unwrap(),
4121 r#"{"kind":"line","text":"boom"}"#
4122 );
4123 assert_eq!(
4124 serde_json::to_value(&stamped).unwrap()["at_ms"],
4125 serde_json::json!(1_789_801_440_685u64)
4126 );
4127 }
4128
4129 #[test]
4130 fn tagged_unknown_values_round_trip_the_original_json() {
4131 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
4132 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4133 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4134 }
4135
4136 #[test]
4137 fn tagged_unknown_values_round_trip_trailing_tag() {
4138 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
4139 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4140 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4141
4142 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
4143 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4144 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4145 }
4146
4147 #[test]
4148 fn tagged_unknown_values_round_trip_middle_tag() {
4149 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
4150 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4151 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4152
4153 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
4154 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4155 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4156 }
4157
4158 #[test]
4159 fn tagged_unknown_values_round_trip_deep_payload() {
4160 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
4161 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4162 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4163
4164 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
4165 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4166 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4167 }
4168
4169 #[test]
4170 fn tagged_unknown_values_reject_non_object_bodies() {
4171 for wire in ["42", r#""future""#, "[]"] {
4172 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
4173 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
4174 }
4175 }
4176
4177 #[test]
4178 fn duplicate_discriminators_reject_without_panicking() {
4179 assert_eq!(
4180 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
4181 .unwrap(),
4182 ModuleDeclaredProvenance::Unverifiable
4183 );
4184 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
4185 .unwrap()
4186 {
4187 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
4188 _ => panic!("future discriminator decoded as a known variant"),
4189 }
4190
4191 let wires = [
4192 r#"{"status":"reported","status":"unverifiable"}"#,
4193 r#"{"status":"unverifiable","status":"reported"}"#,
4194 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4195 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4196 ];
4197
4198 for wire in wires {
4199 let result =
4200 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4201 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4202 assert!(
4203 result.unwrap().is_err(),
4204 "duplicate discriminator decoded: {wire}"
4205 );
4206 }
4207
4208 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4209 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4210 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4211 assert!(
4212 result.unwrap().is_err(),
4213 "duplicate discriminator decoded: {wire}"
4214 );
4215 }
4216
4217 #[test]
4218 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4219 let known_wire =
4220 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4221 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4222 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4223
4224 for wire in [
4225 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4226 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4227 ] {
4228 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4229 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4230 }
4231
4232 for wire in [
4233 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4234 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4235 ] {
4236 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4237 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4238 }
4239
4240 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4241 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4242 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4243
4244 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4245 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4246 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4247 }
4248
4249 #[test]
4250 fn tagged_unknown_member_does_not_discard_known_siblings() {
4251 let body = serde_json::json!({
4252 "modules": [{
4253 "module_id": "target",
4254 "routes": [
4255 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4256 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4257 ]
4258 }]
4259 });
4260 let decoded: ClientControlResponse = serde_json::from_value(
4261 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4262 )
4263 .unwrap();
4264 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4265 panic!("decoded wrong response variant");
4266 };
4267 assert_eq!(modules[0].routes.len(), 2);
4268 assert_eq!(
4269 modules[0].routes[1].consumer,
4270 SupervisorRouteConsumer::Direct { connection_id: 7 }
4271 );
4272 }
4273}
4274
4275#[cfg(test)]
4276mod launch_nonce_redaction_tests {
4277 use super::*;
4278
4279 const NONCE: &str = "nonce-f00dfeed1234abcd";
4280
4281 fn identity() -> ConsumerIdentity {
4282 ConsumerIdentity {
4283 module_id: "wernicke".to_string(),
4284 launch_nonce: NONCE.to_string(),
4285 }
4286 }
4287
4288 #[test]
4289 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4290 let printed = format!("{:?}", identity());
4291 assert!(printed.contains("wernicke"), "{printed}");
4292 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4293 }
4294
4295 #[test]
4296 fn route_open_request_debug_never_prints_the_nonce() {
4297 let request = ClientControlRequest::RouteOpen {
4298 busy_refusals: None,
4299 target: subc_protocol::RouteTarget::ToolProvider {
4300 module_id: "broca".to_string(),
4301 },
4302 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4303 consumer_identity: Some(identity()),
4304 consumer_capabilities: None,
4305 role_versions: None,
4306 admission_facts: None,
4307 scope: None,
4308 };
4309 let printed = format!("{request:?}");
4310 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4311 }
4312}
4313
4314#[cfg(test)]
4315mod reader_skew_tests {
4316 use super::*;
4317 use serde_json::{json, Value};
4318
4319 fn catalog() -> Value {
4320 json!({"module_id": "provider", "roles": [], "control_ops": []})
4321 }
4322
4323 fn reply() -> Value {
4324 json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4325 }
4326
4327 fn target() -> Value {
4328 json!({
4329 "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4330 "authority_epoch": 23, "first_party": true,
4331 "approved_declarations_digest": "approved"
4332 })
4333 }
4334
4335 fn request() -> Value {
4336 json!({
4337 "op": "route.open",
4338 "target": {"kind": "tool_provider", "module_id": "provider"},
4339 "identity": {"harness": "test", "session": "session-1"}
4340 })
4341 }
4342
4343 #[test]
4344 fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4345 let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4346 let built = CatalogEntry::new("provider", vec![], vec![]);
4347 assert_eq!(old, built);
4348 assert_eq!(old.first_party, None);
4349 let old_bytes = serde_json::to_value(&old).unwrap();
4350 let additions = json!({
4351 "incarnation": "daemon", "spawn": 17, "first_party": false,
4352 "origin": "development", "requested_declarations_digest": "requested",
4353 "approved_declarations_digest": "approved"
4354 });
4355 let mut body = catalog();
4356 for (key, value) in additions.as_object().unwrap() {
4357 assert!(old_bytes.get(key).is_none(), "{key}");
4358 body[key] = value.clone();
4359 }
4360 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4361 let encoded = serde_json::to_value(&decoded).unwrap();
4362 for (key, value) in additions.as_object().unwrap() {
4363 assert_eq!(&encoded[key], value, "{key}");
4364 }
4365 assert_eq!(decoded.first_party, Some(false));
4366 assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4367 }
4368
4369 #[test]
4370 fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4371 let mut body = catalog();
4372 body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4373 body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4374 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4375 let encoded = serde_json::to_value(decoded).unwrap();
4376 for key in ["requested_declarations", "approved_declarations"] {
4377 assert_eq!(encoded[key], body[key]);
4378 }
4379 let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4380 assert_eq!(unfiltered.approved_declarations, None);
4381 assert_eq!(unfiltered.requested_declarations, None);
4382 }
4383
4384 #[test]
4385 fn reader_skew_catalog_unknown_origin_is_other() {
4386 let mut body = catalog();
4387 body["origin"] = json!("future-origin");
4388 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4389 assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4390 }
4391
4392 #[test]
4393 fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4394 let mut body = catalog();
4395 body["spawn"] = json!(9_007_199_254_740_991_u64);
4396 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4397 assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4398 for invalid in [
4399 json!(9_007_199_254_740_992_u64),
4400 json!(-1),
4401 json!(1.5),
4402 json!("17"),
4403 ] {
4404 body["spawn"] = invalid;
4405 assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4406 }
4407 }
4408
4409 #[test]
4410 fn reader_skew_catalog_watch_request_uses_subscription_op() {
4411 let body = json!({"op": "catalog.watch"});
4412 let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4413 assert_eq!(request, CatalogWatchRequest::new());
4414 assert_eq!(serde_json::to_value(request).unwrap(), body);
4415 assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4416 for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4417 assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4418 }
4419 }
4420
4421 #[test]
4422 fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4423 for generation in [0, 19, 42] {
4424 let body = json!({"op": "catalog.watch", "generation": generation});
4425 let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4426 assert_eq!(push, CatalogWatchResponse::new(generation));
4427 assert_eq!(serde_json::to_value(push).unwrap(), body);
4428 }
4429 assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4430 for invalid in [
4431 json!({"op": "catalog.watch"}),
4432 json!({"op": "activity.subscribe", "generation": 1}),
4433 ] {
4434 assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4435 }
4436 }
4437
4438 #[test]
4439 fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4440 let mut body = reply();
4441 let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4442 let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4443 assert_eq!(empty, RouteOpenReplyExt::new());
4444 empty.write_to(&mut body).unwrap();
4445 assert_eq!(body, reply());
4446 body["target"] = target();
4447 let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4448 assert_eq!(
4449 decoded.target.as_ref().unwrap().kind,
4450 RouteOpenTargetKind::Spawn
4451 );
4452 let mut encoded = reply();
4453 RouteOpenReplyExt::new()
4454 .with_target(decoded.target)
4455 .write_to(&mut encoded)
4456 .unwrap();
4457 assert_eq!(encoded, body);
4458 assert_eq!(
4459 serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4460 legacy
4461 );
4462 RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4463 assert_eq!(encoded, reply());
4464 }
4465
4466 #[test]
4467 fn reader_skew_route_open_incomplete_target_is_unmarked() {
4468 let mut body = reply();
4469 body["target"] = target();
4470 assert!(RouteOpenReplyExt::read_from(&body)
4471 .unwrap()
4472 .target
4473 .is_some());
4474 for key in [
4475 "incarnation",
4476 "kind",
4477 "spawn",
4478 "authority_epoch",
4479 "first_party",
4480 "approved_declarations_digest",
4481 ] {
4482 let mut incomplete = body.clone();
4483 incomplete["target"].as_object_mut().unwrap().remove(key);
4484 assert_eq!(
4485 RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4486 None,
4487 "{key}"
4488 );
4489 }
4490 body["target"] = Value::Null;
4491 assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4492 }
4493
4494 #[test]
4495 fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4496 for (kind, expected) in [
4497 ("prefix", RouteOpenTargetKind::Prefix),
4498 ("unsupervised", RouteOpenTargetKind::Unsupervised),
4499 ] {
4500 let mut body = reply();
4501 body["target"] = target();
4502 body["target"]["kind"] = json!(kind);
4503 body["target"]["spawn"] = json!("not-a-spawn");
4505 body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4506 body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4507 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4508 let target = ext.target.as_ref().unwrap();
4509 assert_eq!(target.kind, expected);
4510 assert_eq!(target.spawn, None);
4511 assert_eq!(target.authority_epoch, None);
4512 assert_eq!(target.approved_declarations_digest, None);
4513 assert!(!target.first_party);
4514 let mut encoded = reply();
4515 ext.write_to(&mut encoded).unwrap();
4516 for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
4517 assert!(encoded["target"].get(key).is_none());
4518 }
4519 }
4520 }
4521
4522 #[test]
4523 fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4524 let mut body = reply();
4525 body["target"] = target();
4526 body["target"]["kind"] = json!("future-kind");
4527 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4528 let target = ext.target.unwrap();
4529 assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4530 assert_eq!(target.spawn, None);
4531 assert_eq!(target.authority_epoch, None);
4532 assert_eq!(target.approved_declarations_digest, None);
4533 assert!(!target.first_party);
4534 }
4535
4536 #[test]
4537 fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4538 for field in ["spawn", "authority_epoch"] {
4539 let mut body = reply();
4540 body["target"] = target();
4541 body["target"][field] = json!(9_007_199_254_740_991_u64);
4542 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4543 assert_eq!(
4544 serde_json::to_value(ext).unwrap()["target"][field],
4545 9_007_199_254_740_991_u64
4546 );
4547 for invalid in [
4548 json!(9_007_199_254_740_992_u64),
4549 json!(-1),
4550 json!(1.5),
4551 json!("17"),
4552 ] {
4553 body["target"][field] = invalid;
4554 assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4555 let mut incomplete = body.clone();
4556 incomplete["target"]
4557 .as_object_mut()
4558 .unwrap()
4559 .remove("incarnation");
4560 assert!(
4561 RouteOpenReplyExt::read_from(&incomplete).is_err(),
4562 "{field}"
4563 );
4564 }
4565 }
4566 }
4567
4568 #[test]
4569 fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4570 let mut body = request();
4571 let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4572 assert_eq!(
4573 RouteOpenRequestExt::read_from(&body).unwrap(),
4574 RouteOpenRequestExt::new()
4575 );
4576 RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4577 assert_eq!(body, request());
4578 body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4579 let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4580 assert_eq!(
4581 decoded.accepts_close_reasons,
4582 Some(vec!["authority_changed".into(), "future-reason".into()])
4583 );
4584 let mut encoded = request();
4585 RouteOpenRequestExt::new()
4586 .with_accepts_close_reasons(decoded.accepts_close_reasons)
4587 .write_to(&mut encoded)
4588 .unwrap();
4589 assert_eq!(encoded, body);
4590 assert_eq!(
4591 serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4592 legacy
4593 );
4594 RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4595 assert_eq!(encoded, request());
4596 assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4597 }
4598
4599 #[test]
4600 fn reader_skew_route_open_helpers_refuse_other_bodies() {
4601 for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4602 assert!(RouteOpenRequestExt::read_from(&body).is_err());
4603 assert!(RouteOpenReplyExt::read_from(&body).is_err());
4604 assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4605 assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4606 }
4607 }
4608
4609 #[test]
4610 fn reader_skew_route_open_target_constructor_validates_like_reader() {
4611 let spawn = RouteOpenTarget::new(
4612 "daemon",
4613 RouteOpenTargetKind::Spawn,
4614 Some(17),
4615 Some(23),
4616 true,
4617 Some("approved".into()),
4618 )
4619 .unwrap();
4620 assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4621 for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4622 assert!(RouteOpenTarget::new(
4623 "daemon",
4624 RouteOpenTargetKind::Spawn,
4625 Some(spawn),
4626 Some(epoch),
4627 true,
4628 Some("approved".into())
4629 )
4630 .is_err());
4631 }
4632 }
4633}
4634
4635#[cfg(test)]
4636mod claim_wire_tests {
4637 use super::*;
4638 use serde_json::{json, Value};
4639
4640 fn legacy_provenance() -> SupervisorModuleProvenance {
4641 SupervisorModuleProvenance {
4642 module_id: "worker".into(),
4643 module_declared: ModuleDeclaredProvenance::Unverifiable,
4644 daemon_observed: SupervisorObservedProcess {
4645 launch_nonce_source: None,
4646 pid: None,
4647 spawned_at_ms: None,
4648 spawned_from: None,
4649 running_image: RunningImageAgreement::Unavailable {
4650 reason: RunningImageUnavailableReason::NotRunning,
4651 },
4652 },
4653 }
4654 }
4655
4656 #[test]
4657 fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4658 let legacy = legacy_provenance();
4659 let original = serde_json::to_value(&legacy).unwrap();
4660 let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4661 assert_eq!(absent.registration, None);
4662 let mut wire = original.clone();
4663 absent.write_to(&mut wire).unwrap();
4664 assert_eq!(wire, original);
4665 for (method, spelling) in [
4666 (RegistrationMethod::Channel, "channel"),
4667 (RegistrationMethod::Nonce, "nonce"),
4668 ] {
4669 let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4670 ext.write_to(&mut wire).unwrap();
4671 assert_eq!(wire["registration"], spelling);
4672 assert_eq!(
4673 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4674 ext
4675 );
4676 let old_reader: SupervisorModuleProvenance =
4677 serde_json::from_value(wire.clone()).unwrap();
4678 assert_eq!(old_reader, legacy);
4679 assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4680 }
4681 absent.write_to(&mut wire).unwrap();
4682 assert_eq!(wire, original);
4683 for mut invalid in [Value::Null, json!([]), json!("entry")] {
4684 assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4685 assert!(absent.write_to(&mut invalid).is_err());
4686 }
4687 }
4688
4689 #[test]
4690 fn provenance_waiting_previous_detail_preserves_legacy_entry() {
4691 let legacy = legacy_provenance();
4692 let mut wire = serde_json::to_value(&legacy).unwrap();
4693 let absent = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4694 assert_eq!(absent.waiting_for_previous_detail, None);
4695 let detail = "waiting: container survivors (pids [42])";
4696 let ext = absent
4697 .clone()
4698 .with_waiting_for_previous_detail(Some(detail.into()));
4699 ext.write_to(&mut wire).unwrap();
4700 assert_eq!(wire["waiting_for_previous_detail"], detail);
4701 assert_eq!(
4702 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4703 ext
4704 );
4705 assert_eq!(
4706 serde_json::from_value::<SupervisorModuleProvenance>(wire.clone()).unwrap(),
4707 legacy
4708 );
4709 absent.write_to(&mut wire).unwrap();
4710 assert!(wire.get("waiting_for_previous_detail").is_none());
4711 }
4712
4713 #[test]
4714 fn provenance_unknown_registration_is_not_channel_or_nonce() {
4715 let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4716 wire["registration"] = json!("future_method");
4717 let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4718 assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4719 assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4720 assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4721 wire["registration"] = json!(false);
4722 assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4723 }
4724
4725 #[test]
4726 fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4727 let original = serde_json::to_value(legacy_provenance()).unwrap();
4728 for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4729 let mut golden = original.clone();
4730 golden["registration_declaration"] = json!(declaration);
4731 let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4732 assert_eq!(
4733 serde_json::to_value(&extension).unwrap(),
4734 json!({
4735 "registration_declaration": declaration
4736 })
4737 );
4738 let mut written = original.clone();
4739 extension.write_to(&mut written).unwrap();
4740 assert_eq!(written, golden);
4741 assert_eq!(
4742 serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4743 legacy_provenance()
4744 );
4745 SupervisorModuleProvenanceExt::new()
4746 .write_to(&mut written)
4747 .unwrap();
4748 assert_eq!(written, original);
4749 }
4750 }
4751
4752 #[test]
4753 fn admission_refusal_is_optional_and_open() {
4754 let entry = SupervisorEntry::new(
4755 "worker",
4756 "stopped",
4757 true,
4758 false,
4759 SupervisorHealthStatus::Unknown,
4760 );
4761 let original = serde_json::to_value(&entry).unwrap();
4762 assert!(original.get("admission_refused").is_none());
4763 let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
4764 assert_eq!(read.admission_refused, None);
4765 assert_eq!(serde_json::to_value(read).unwrap(), original);
4766 assert_eq!(
4767 REGISTRATION_CHANNEL_UNSUPPORTED,
4768 "registration_channel_unsupported"
4769 );
4770 for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
4771 let mut wire = original.clone();
4772 wire["admission_refused"] = json!(reason);
4773 let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
4774 assert_eq!(read.admission_refused.as_deref(), Some(reason));
4775 assert_eq!(serde_json::to_value(read).unwrap(), wire);
4776 let built = entry.clone().with_admission_refused(Some(reason.into()));
4777 assert_eq!(serde_json::to_value(built).unwrap(), wire);
4778 }
4779 }
4780}