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::*;
95mod app_trust;
96pub use app_trust::*;
97
98mod connection_describe;
99pub use connection_describe::*;
100
101mod scope_watch;
102pub use scope_watch::*;
103
104mod subtree;
105pub use subtree::*;
106mod tree;
107pub use tree::*;
108
109#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
111pub struct ConsumerIdentity {
112 pub module_id: String,
113 pub launch_nonce: String,
114}
115
116impl std::fmt::Debug for ConsumerIdentity {
121 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122 f.debug_struct("ConsumerIdentity")
123 .field("module_id", &self.module_id)
124 .field(
125 "launch_nonce",
126 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
127 )
128 .finish()
129 }
130}
131
132pub mod config;
143
144pub mod ops {
145 pub const SERVER: &str = "server.";
146 pub const CATALOG: &str = "catalog.";
147 pub const ROUTE: &str = "route.";
148 pub const SUPERVISOR: &str = "supervisor.";
149 pub const CONFIG: &str = "config.";
150
151 pub const SERVER_DESCRIBE: &str = "server.describe";
152 pub const DAEMON_SHUTDOWN_INTENT: &str = "daemon.shutdown_intent";
153 pub const DAEMON_UPGRADE_IN_PLACE: &str = "daemon.upgrade_in_place";
154 pub const CATALOG_LIST: &str = "catalog.list";
155 pub const CATALOG_WATCH: &str = "catalog.watch";
156 pub const SCOPE_WATCH: &str = "scope.watch";
157 pub const ROUTE_OPEN: &str = "route.open";
158 pub const ROUTE_POLL: &str = "route.poll";
159 pub const ROUTE_CLOSING: &str = "route.closing";
160 pub const ROUTE_CLOSED: &str = "route.closed";
161 pub const SUPERVISOR_LIST: &str = "supervisor.list";
162 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
163 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
164 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
165 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
166 pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
167 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
168 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
169 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
170 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
171 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
172 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
173 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
174 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
175 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
176 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
177 pub const ACTIVITY_RECORD: &str = "activity.record";
178 pub const ACTIVITY_QUERY: &str = "activity.query";
179 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
180 pub const APP_OPEN: &str = "app.open";
181 pub const APP_TRUST: &str = "app.trust";
182 pub const APP_TRUSTED: &str = "app.trusted";
183 pub const APP_UNTRUST: &str = "app.untrust";
184 pub const CONNECTION_DESCRIBE: &str = "connection.describe";
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
189#[serde(tag = "op")]
190#[allow(clippy::large_enum_variant)]
193pub enum ClientControlRequest {
194 #[serde(rename = "policy_root.get")]
195 PolicyRoot(subc_protocol::policy_root::GetPolicyRoot),
196 #[serde(rename = "policy_root.set")]
197 PolicyRootSet(policy_root::SetPolicyRoot),
198 #[serde(rename = "policy_root.recover")]
199 PolicyRootRecover(policy_root::RecoverPolicyRoot),
200 #[serde(rename = "daemon.shutdown_intent")]
203 DaemonShutdownIntent {
204 #[serde(default)]
205 intent: serde_json::Value,
206 },
207 #[serde(rename = "daemon.upgrade_in_place")]
208 DaemonUpgradeInPlace { executable_sha256: String },
209 #[serde(rename = "server.describe")]
210 ServerDescribe {},
211 #[serde(rename = "catalog.list")]
212 CatalogList {
213 #[serde(default)]
218 module_id: Option<String>,
219 },
220 #[serde(rename = "route.open")]
221 RouteOpen {
222 target: RouteTarget,
223 identity: BindIdentity,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
233 consumer_identity: Option<ConsumerIdentity>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
242 consumer_capabilities: Option<Vec<String>>,
243 #[serde(default, skip_serializing_if = "Option::is_none")]
254 role_versions: Option<BTreeMap<String, String>>,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
259 busy_refusals: Option<bool>,
260 #[serde(default, skip_serializing_if = "Option::is_none")]
262 admission_facts: Option<serde_json::Value>,
263 #[serde(default, skip_serializing_if = "Option::is_none")]
270 scope: Option<ScopeSelector>,
271 },
272 #[serde(rename = "route.poll")]
273 RoutePoll {
274 route_channel: u16,
275 route_epoch: u32,
276 kind: PollKind,
277 },
278 #[serde(rename = "supervisor.list")]
279 SupervisorList {},
280 #[serde(rename = "supervisor.spawn_snapshot")]
282 SupervisorSpawnSnapshot {},
283 #[serde(rename = "supervisor.spawn_subscribe")]
299 SupervisorSpawnSubscribe {
300 #[serde(default, skip_serializing_if = "Option::is_none")]
301 since: Option<SpawnCursor>,
302 },
303 #[serde(rename = "supervisor.restart")]
304 SupervisorRestart {
305 module_id: String,
306 #[serde(default, skip_serializing_if = "Option::is_none")]
316 drain_timeout_ms: Option<u64>,
317 },
318 #[serde(rename = "supervisor.swap")]
333 SupervisorSwap {
334 module_id: String,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
338 ready_timeout_ms: Option<u64>,
339 },
340 #[serde(rename = "supervisor.reload")]
341 SupervisorReload { module_id: String },
342 #[serde(rename = "supervisor.rescan")]
343 SupervisorRescan {
344 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
364 preview: bool,
365 },
366 #[serde(rename = "supervisor.rescan_checked")]
390 SupervisorRescanChecked {
391 preview: bool,
392 #[serde(default, skip_serializing_if = "Option::is_none")]
393 candidate: Option<String>,
394 #[serde(default, skip_serializing_if = "Option::is_none")]
395 expect: Option<RescanExpect>,
396 },
397 #[serde(rename = "supervisor.release_reserved")]
401 SupervisorReleaseReserved { module_id: String },
402 #[serde(rename = "supervisor.set_enabled")]
403 SupervisorSetEnabled { module_id: String, enabled: bool },
404 #[serde(rename = "supervisor.health_probe")]
405 SupervisorHealthProbe { module_id: String },
406 #[serde(rename = "supervisor.health")]
407 SupervisorHealth {},
408 #[serde(rename = "supervisor.routes")]
421 SupervisorRoutes {
422 #[serde(default, skip_serializing_if = "Option::is_none")]
423 module_id: Option<String>,
424 },
425 #[serde(rename = "supervisor.provenance")]
428 SupervisorProvenance {
429 #[serde(default, skip_serializing_if = "Option::is_none")]
430 module_id: Option<String>,
431 },
432 #[serde(rename = "supervisor.stderr_tail")]
440 SupervisorStderrTail {
441 module_id: String,
442 #[serde(default, skip_serializing_if = "Option::is_none")]
443 max_lines: Option<u32>,
444 #[serde(default, skip_serializing_if = "Option::is_none")]
445 max_bytes: Option<u32>,
446 },
447 #[serde(rename = "supervisor.terminals")]
460 SupervisorTerminals { module_id: String },
461}
462
463#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
465#[serde(tag = "op")]
466pub enum ClientControlResponse {
467 #[serde(rename = "policy_root.get")]
468 PolicyRoot(subc_protocol::policy_root::PolicyRoot),
469 #[serde(rename = "policy_root.set")]
470 PolicyRootSet(subc_protocol::policy_root::PolicyRootChange),
471 #[serde(rename = "policy_root.recover")]
472 PolicyRootRecover(subc_protocol::policy_root::PolicyRootChange),
473 #[serde(rename = "daemon.shutdown_intent")]
474 DaemonShutdownIntent { intent: String, expires_at_ms: u64 },
475 #[serde(rename = "server.describe")]
476 ServerDescribe {
477 protocol_ver: u8,
478 subc_ops: Vec<String>,
479 capabilities: Vec<String>,
480 connected_clients: u64,
481 #[serde(default, skip_serializing_if = "Option::is_none")]
482 counters: Option<serde_json::Value>,
483 #[serde(default, skip_serializing_if = "Option::is_none")]
490 build_git_sha: Option<String>,
491 #[serde(default, skip_serializing_if = "Option::is_none")]
497 build_lock_digest: Option<String>,
498 #[serde(default, skip_serializing_if = "Vec::is_empty")]
502 capability_requirements: Vec<CapabilityRequirementStatus>,
503 #[serde(default, skip_serializing_if = "Option::is_none")]
508 machine_id: Option<String>,
509 #[serde(default, skip_serializing_if = "Option::is_none")]
518 config_path: Option<PathBuf>,
519 #[serde(default, skip_serializing_if = "Option::is_none")]
521 pid: Option<u32>,
522 #[serde(default, skip_serializing_if = "Option::is_none")]
526 uptime_ms: Option<u64>,
527 },
528 #[serde(rename = "catalog.list")]
529 CatalogList {
530 generation: u64,
531 modules: Vec<CatalogEntry>,
532 subc_ops: Vec<String>,
533 },
534 #[serde(rename = "route.open")]
535 RouteOpen {
536 route_channel: u16,
537 route_epoch: u32,
538 #[serde(default, skip_serializing_if = "Option::is_none")]
540 request_window: Option<usize>,
541 #[serde(default, skip_serializing_if = "Option::is_none")]
543 watch_window: Option<usize>,
544 },
545 #[serde(rename = "route.poll")]
546 RoutePoll {
547 route_channel: u16,
548 route_epoch: u32,
549 status: Option<String>,
550 live: Option<bool>,
551 },
552 #[serde(rename = "supervisor.list")]
553 SupervisorList {
554 generation: u64,
555 modules: Vec<SupervisorEntry>,
556 #[serde(default, skip_serializing_if = "Option::is_none")]
557 daemon: Option<DaemonResources>,
558 #[serde(default, skip_serializing_if = "Option::is_none")]
559 agent_commands: Option<Vec<AgentCommandResources>>,
560 },
561 #[serde(rename = "supervisor.spawn_snapshot")]
562 SupervisorSpawnSnapshot {
563 #[serde(flatten)]
564 snapshot: SpawnSnapshot,
565 },
566 #[serde(rename = "supervisor.ack")]
567 SupervisorAck { module_id: String, applied: bool },
568 #[serde(rename = "supervisor.rescan")]
569 SupervisorRescan {
570 #[serde(flatten)]
571 result: SupervisorRescanResult,
572 },
573 #[serde(rename = "supervisor.health_probe")]
574 SupervisorHealthProbe {
575 module_id: String,
576 status: HealthStatus,
577 #[serde(default, skip_serializing_if = "Option::is_none")]
578 detail: Option<String>,
579 #[serde(default, skip_serializing_if = "Option::is_none")]
580 metrics: Option<serde_json::Value>,
581 },
582 #[serde(rename = "supervisor.health")]
583 SupervisorHealth {
584 generation: u64,
585 modules: Vec<SupervisorHealthEntry>,
586 },
587 #[serde(rename = "supervisor.routes")]
588 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
589 #[serde(rename = "supervisor.provenance")]
590 SupervisorProvenance {
591 daemon: SupervisorDaemonProvenance,
592 modules: Vec<SupervisorModuleProvenance>,
593 },
594 #[serde(rename = "supervisor.stderr_tail")]
595 SupervisorStderrTail {
596 module_id: String,
597 #[serde(flatten)]
598 tail: StderrTail,
599 },
600 #[serde(rename = "supervisor.terminals")]
601 SupervisorTerminals {
602 module_id: String,
603 #[serde(flatten)]
604 terminals: TerminalHistory,
605 },
606}
607
608pub const ROUTE_CLOSE_REASONS_CAPABILITY: &str = "route-close-reasons/v1";
610
611#[non_exhaustive]
615#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
616pub struct RouteOpenRequestExt {
617 #[serde(default, skip_serializing_if = "Option::is_none")]
618 pub accepts_close_reasons: Option<Vec<String>>,
619}
620
621impl RouteOpenRequestExt {
622 pub fn new() -> Self {
623 Self::default()
624 }
625
626 #[must_use]
627 pub fn with_accepts_close_reasons(mut self, reasons: Option<Vec<String>>) -> Self {
628 self.accepts_close_reasons = reasons;
629 self
630 }
631
632 pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
634 require_route_open_object(body)?;
635 serde_json::from_value(body.clone())
636 }
637
638 pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
641 write_route_open_ext(body, self, &["accepts_close_reasons"])
642 }
643}
644
645#[non_exhaustive]
648#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
649pub struct RouteOpenReplyExt {
650 #[serde(
652 default,
653 skip_serializing_if = "Option::is_none",
654 deserialize_with = "deserialize_route_open_target"
655 )]
656 pub target: Option<RouteOpenTarget>,
657}
658
659impl RouteOpenReplyExt {
660 pub fn new() -> Self {
661 Self::default()
662 }
663
664 #[must_use]
665 pub fn with_target(mut self, target: Option<RouteOpenTarget>) -> Self {
666 self.target = target;
667 self
668 }
669
670 pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
672 require_route_open_object(body)?;
673 serde_json::from_value(body.clone())
674 }
675
676 pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
679 write_route_open_ext(body, self, &["target"])
680 }
681}
682
683fn require_route_open_object(body: &serde_json::Value) -> serde_json::Result<()> {
684 if body.is_object()
685 && body.get("op").and_then(serde_json::Value::as_str) == Some(ops::ROUTE_OPEN)
686 {
687 Ok(())
688 } else {
689 Err(serde_json::Error::custom(
690 "expected a route.open body object",
691 ))
692 }
693}
694
695fn write_route_open_ext(
696 body: &mut serde_json::Value,
697 ext: &impl Serialize,
698 keys: &[&str],
699) -> serde_json::Result<()> {
700 require_route_open_object(body)?;
701 let serde_json::Value::Object(fields) = serde_json::to_value(ext)? else {
702 unreachable!("route.open companions serialize as objects");
703 };
704 let object = body.as_object_mut().expect("validated route.open object");
705 for key in keys {
706 object.remove(*key);
707 }
708 object.extend(fields);
709 Ok(())
710}
711
712#[non_exhaustive]
714#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
715#[serde(rename_all = "snake_case")]
716pub enum RouteOpenTargetKind {
717 Spawn,
718 Prefix,
719 Unsupervised,
720 #[serde(other)]
721 Unknown,
722}
723
724#[non_exhaustive]
727#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
728pub struct RouteOpenTarget {
729 pub incarnation: String,
730 pub kind: RouteOpenTargetKind,
731 #[serde(skip_serializing_if = "Option::is_none")]
732 pub spawn: Option<u64>,
733 #[serde(skip_serializing_if = "Option::is_none")]
734 pub authority_epoch: Option<u64>,
735 pub first_party: bool,
736 #[serde(skip_serializing_if = "Option::is_none")]
737 pub approved_declarations_digest: Option<String>,
738}
739
740impl RouteOpenTarget {
741 pub fn new(
744 incarnation: impl Into<String>,
745 kind: RouteOpenTargetKind,
746 spawn: Option<u64>,
747 authority_epoch: Option<u64>,
748 first_party: bool,
749 approved_declarations_digest: Option<String>,
750 ) -> serde_json::Result<Self> {
751 serde_json::from_value(serde_json::json!({
752 "incarnation": incarnation.into(), "kind": kind,
753 "spawn": spawn, "authority_epoch": authority_epoch,
754 "first_party": first_party,
755 "approved_declarations_digest": approved_declarations_digest,
756 }))
757 }
758}
759
760impl<'de> Deserialize<'de> for RouteOpenTarget {
761 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
762 decode_route_open_target(serde_json::Value::deserialize(decoder)?)
763 .map_err(D::Error::custom)?
764 .ok_or_else(|| D::Error::custom("incomplete route.open target"))
765 }
766}
767
768fn deserialize_route_open_target<'de, D: Deserializer<'de>>(
769 decoder: D,
770) -> Result<Option<RouteOpenTarget>, D::Error> {
771 decode_route_open_target(serde_json::Value::deserialize(decoder)?).map_err(D::Error::custom)
772}
773
774fn decode_route_open_target(
775 mut value: serde_json::Value,
776) -> serde_json::Result<Option<RouteOpenTarget>> {
777 if value.is_null() {
778 return Ok(None);
779 }
780 let object = value
781 .as_object_mut()
782 .ok_or_else(|| serde_json::Error::custom("expected target object"))?;
783 let is_spawn = object.get("kind").and_then(serde_json::Value::as_str) == Some("spawn");
784 if is_spawn {
785 for field in ["spawn", "authority_epoch"] {
787 if let Some(integer) = object.get(field) {
788 deserialize_optional_attestation_integer(integer)?;
789 }
790 }
791 } else {
792 for field in ["spawn", "authority_epoch", "approved_declarations_digest"] {
793 object.remove(field);
794 }
795 }
796 if ["incarnation", "kind", "first_party"]
797 .iter()
798 .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null))
799 || (is_spawn
800 && ["spawn", "authority_epoch", "approved_declarations_digest"]
801 .iter()
802 .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null)))
803 {
804 return Ok(None);
805 }
806 #[derive(Deserialize)]
807 struct Wire {
808 incarnation: String,
809 kind: RouteOpenTargetKind,
810 spawn: Option<u64>,
811 authority_epoch: Option<u64>,
812 first_party: bool,
813 approved_declarations_digest: Option<String>,
814 }
815 let wire: Wire = serde_json::from_value(value)?;
816 Ok(Some(RouteOpenTarget {
817 incarnation: wire.incarnation,
818 kind: wire.kind,
819 spawn: wire.spawn,
820 authority_epoch: wire.authority_epoch,
821 first_party: is_spawn && wire.first_party,
822 approved_declarations_digest: wire.approved_declarations_digest,
823 }))
824}
825
826fn deserialize_optional_attestation_integer<'de, D: Deserializer<'de>>(
827 decoder: D,
828) -> Result<Option<u64>, D::Error> {
829 let value = Option::<u64>::deserialize(decoder)?;
830 if value.is_some_and(|integer| integer > MAX_ATTESTATION_INTEGER) {
831 return Err(D::Error::custom("attestation integer exceeds 2^53-1"));
832 }
833 Ok(value)
834}
835
836#[non_exhaustive]
839#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
840#[serde(tag = "op", rename = "catalog.watch")]
841pub struct CatalogWatchRequest {}
842
843impl CatalogWatchRequest {
844 pub const OP: &'static str = ops::CATALOG_WATCH;
845
846 pub fn new() -> Self {
847 Self {}
848 }
849}
850
851#[non_exhaustive]
855#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
856#[serde(tag = "op", rename = "catalog.watch")]
857pub struct CatalogWatchResponse {
858 pub generation: u64,
859}
860
861impl CatalogWatchResponse {
862 pub const OP: &'static str = ops::CATALOG_WATCH;
863
864 pub fn new(generation: u64) -> Self {
865 Self { generation }
866 }
867}
868
869impl<'de> Deserialize<'de> for CatalogWatchRequest {
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 {},
876 }
877 let Wire::Body {} = Wire::deserialize(decoder)?;
878 Ok(Self::new())
879 }
880}
881
882impl<'de> Deserialize<'de> for CatalogWatchResponse {
883 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
884 #[derive(Deserialize)]
885 #[serde(tag = "op")]
886 enum Wire {
887 #[serde(rename = "catalog.watch")]
888 Body { generation: u64 },
889 }
890 let Wire::Body { generation } = Wire::deserialize(decoder)?;
891 Ok(Self::new(generation))
892 }
893}
894
895#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
900#[serde(tag = "op")]
901pub enum ClientControlPush {
902 #[serde(rename = "route.closing")]
903 RouteClosing {
904 module_id: String,
905 #[serde(default)]
908 channels: Vec<u16>,
909 reason: RouteCloseReason,
910 },
911 #[serde(rename = "route.closed")]
912 RouteClosed {
913 module_id: String,
914 #[serde(default)]
917 channels: Vec<u16>,
918 reason: RouteCloseReason,
919 drained: bool,
921 abandoned: u32,
924 #[serde(default)]
926 excluded_subscriptions: u32,
927 #[serde(default, skip_serializing_if = "Option::is_none")]
933 terminal: Option<bool>,
934 },
935}
936
937#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
939pub struct SpawnCursor {
940 pub daemon_incarnation: String,
941 pub seq: u64,
942}
943
944#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
946pub struct LiveSpawn {
947 pub module_id: String,
948 pub spawn_generation: u64,
954 pub pid: u32,
955 pub spawned_at_ms: u64,
956}
957
958#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
960pub struct SpawnSnapshot {
961 pub cursor: SpawnCursor,
962 pub ring_bound: u64,
964 pub live: Vec<LiveSpawn>,
965}
966
967#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
969#[serde(rename_all = "snake_case")]
970pub enum SpawnEventKind {
971 Spawned,
972 Exited,
973}
974
975#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
981pub struct SpawnEvent {
982 pub cursor: SpawnCursor,
983 pub kind: SpawnEventKind,
984 pub module_id: String,
985 pub spawn_generation: u64,
987 pub pid: u32,
988 #[serde(default, skip_serializing_if = "Option::is_none")]
989 pub exit_code: Option<i32>,
990 #[serde(default, skip_serializing_if = "Option::is_none")]
991 pub exit_signal: Option<i32>,
992}
993
994#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
996pub struct StderrTail {
997 pub capture: StderrCaptureState,
998 pub entries: Vec<StderrTailEntry>,
999 #[serde(default, skip_serializing_if = "is_zero_u64")]
1008 pub dropped_lines: u64,
1009}
1010
1011#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1013pub struct SupervisorRouteModule {
1014 pub module_id: String,
1015 pub routes: Vec<SupervisorRoute>,
1016}
1017
1018#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1020pub struct SupervisorRoute {
1021 pub consumer: SupervisorRouteConsumer,
1022 pub age_ms: u64,
1024 pub draining: bool,
1027 #[serde(default, skip_serializing_if = "Option::is_none")]
1033 pub drain_reason: Option<RouteCloseReason>,
1034 #[serde(default, skip_serializing_if = "Option::is_none")]
1036 pub opener: Option<SupervisorRouteOpener>,
1037}
1038
1039#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1041pub struct SupervisorRouteOpener {
1042 pub connection_id: u64,
1043 pub transport: SupervisorRouteTransport,
1044 #[serde(default, skip_serializing_if = "Option::is_none")]
1045 pub pid: Option<u32>,
1046 #[serde(default, skip_serializing_if = "Option::is_none")]
1047 pub command: Option<String>,
1048}
1049
1050#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1052#[serde(rename_all = "snake_case")]
1053pub enum SupervisorRouteTransport {
1054 Local,
1055 Tcp,
1056}
1057
1058#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1060pub struct SupervisorModuleProvenance {
1061 pub module_id: String,
1062 pub module_declared: ModuleDeclaredProvenance,
1063 pub daemon_observed: SupervisorObservedProcess,
1064}
1065
1066#[non_exhaustive]
1069#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1070pub struct SupervisorModuleProvenanceExt {
1071 #[serde(default, skip_serializing_if = "Option::is_none")]
1073 pub registration: Option<RegistrationMethod>,
1074 #[serde(default, skip_serializing_if = "Option::is_none")]
1078 pub registration_declaration: Option<String>,
1079 #[serde(default, skip_serializing_if = "Option::is_none")]
1081 pub waiting_for_previous_detail: Option<String>,
1082}
1083
1084impl SupervisorModuleProvenanceExt {
1085 pub fn new() -> Self {
1086 Self::default()
1087 }
1088
1089 #[must_use]
1090 pub fn with_registration(mut self, registration: Option<RegistrationMethod>) -> Self {
1091 self.registration = registration;
1092 self
1093 }
1094
1095 #[must_use]
1096 pub fn with_waiting_for_previous_detail(mut self, detail: Option<String>) -> Self {
1097 self.waiting_for_previous_detail = detail;
1098 self
1099 }
1100
1101 pub fn read_from(entry: &serde_json::Value) -> serde_json::Result<Self> {
1103 if !entry.is_object() {
1104 return Err(serde_json::Error::custom(
1105 "expected a module provenance entry object",
1106 ));
1107 }
1108 serde_json::from_value(entry.clone())
1109 }
1110
1111 pub fn write_to(&self, entry: &mut serde_json::Value) -> serde_json::Result<()> {
1114 let object = entry.as_object_mut().ok_or_else(|| {
1115 serde_json::Error::custom("expected a module provenance entry object")
1116 })?;
1117 object.remove("registration");
1118 if let Some(method) = &self.registration {
1119 object.insert("registration".into(), serde_json::to_value(method)?);
1120 }
1121 object.remove("registration_declaration");
1122 if let Some(declaration) = &self.registration_declaration {
1123 object.insert(
1124 "registration_declaration".into(),
1125 declaration.clone().into(),
1126 );
1127 }
1128 object.remove("waiting_for_previous_detail");
1129 if let Some(detail) = &self.waiting_for_previous_detail {
1130 object.insert("waiting_for_previous_detail".into(), detail.clone().into());
1131 }
1132 Ok(())
1133 }
1134}
1135
1136#[non_exhaustive]
1139#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1140#[serde(rename_all = "snake_case")]
1141pub enum RegistrationMethod {
1142 Channel,
1143 Nonce,
1144 #[serde(other)]
1145 Unknown,
1146}
1147
1148pub const REGISTRATION_CHANNEL_UNSUPPORTED: &str = "registration_channel_unsupported";
1151
1152#[derive(Debug, Clone, PartialEq)]
1154pub enum ModuleDeclaredProvenance {
1155 Reported {
1156 build: ManifestProvenance,
1157 },
1158 Unverifiable,
1159 Unknown {
1162 tag: String,
1163 body: OrderedJsonObject,
1164 },
1165}
1166
1167#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1172pub struct SupervisorObservedProcess {
1173 #[serde(default, skip_serializing_if = "Option::is_none")]
1179 pub launch_nonce_source: Option<String>,
1180 #[serde(default, skip_serializing_if = "Option::is_none")]
1181 pub pid: Option<u32>,
1182 #[serde(default, skip_serializing_if = "Option::is_none")]
1183 pub spawned_at_ms: Option<u64>,
1184 #[serde(default, skip_serializing_if = "Option::is_none")]
1185 pub spawned_from: Option<PathBuf>,
1186 pub running_image: RunningImageAgreement,
1187}
1188
1189#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1206#[non_exhaustive]
1207pub struct PendingReloadVerdict {
1208 pub path: ReloadPathAgreement,
1209 pub image: RunningImageAgreement,
1210 #[serde(default, skip_serializing_if = "Option::is_none")]
1211 pub spec: Option<LaunchSpecAgreement>,
1212}
1213
1214impl PendingReloadVerdict {
1215 #[must_use]
1217 pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
1218 Self {
1219 path,
1220 image,
1221 spec: None,
1222 }
1223 }
1224
1225 #[must_use]
1227 pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
1228 self.spec = spec;
1229 self
1230 }
1231}
1232
1233#[cfg(test)]
1234mod launch_spec_wire_tests {
1235 use super::*;
1236
1237 #[test]
1238 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
1239 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
1240 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
1241 assert_eq!(parsed.spec, None);
1242 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
1243 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
1244 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
1245 assert!(
1246 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
1247 );
1248 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
1249 let unavailable = LaunchSpecAgreement::Unavailable {
1250 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
1251 };
1252 let encoded = serde_json::to_string(&unavailable).unwrap();
1253 assert_eq!(
1254 encoded,
1255 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
1256 );
1257 assert_eq!(
1258 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
1259 unavailable
1260 );
1261 }
1262}
1263
1264#[derive(Debug, Clone, PartialEq)]
1267pub enum LaunchSpecAgreement {
1268 Match,
1269 Mismatch,
1270 Unavailable {
1271 reason: LaunchSpecUnavailableReason,
1272 },
1273 Unknown {
1274 tag: String,
1275 body: OrderedJsonObject,
1276 },
1277}
1278
1279open_string_enum! {
1280 LaunchSpecUnavailableReason {
1281 NotRunning => "not_running",
1282 SpawnedSpecUnavailable => "spawned_spec_unavailable",
1283 }
1284}
1285
1286#[derive(Debug, Clone, PartialEq)]
1288pub enum ReloadPathAgreement {
1289 Match,
1290 Mismatch {
1291 configured: PathBuf,
1292 spawned_from: PathBuf,
1293 },
1294 Unavailable {
1295 reason: ReloadPathUnavailableReason,
1296 },
1297 Unknown {
1298 tag: String,
1299 body: OrderedJsonObject,
1300 },
1301}
1302
1303open_string_enum! {
1304 ReloadPathUnavailableReason {
1306 NotRunning => "not_running",
1307 SpawnedPathUnavailable => "spawned_path_unavailable",
1308 }
1309}
1310
1311#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1313pub struct SupervisorDaemonProvenance {
1314 pub daemon_build: DaemonBuildProvenance,
1315 pub daemon_observed: DaemonObservedProcess,
1316}
1317
1318#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1320pub struct DaemonBuildProvenance {
1321 #[serde(default, skip_serializing_if = "Option::is_none")]
1322 pub build_git_sha: Option<String>,
1323 #[serde(default, skip_serializing_if = "Option::is_none")]
1324 pub build_lock_digest: Option<String>,
1325}
1326
1327#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1329pub struct DaemonObservedProcess {
1330 #[serde(default, skip_serializing_if = "Option::is_none")]
1331 pub pid: Option<u32>,
1332 #[serde(default, skip_serializing_if = "Option::is_none")]
1337 pub started_at_ms: Option<u64>,
1338 pub running_image: RunningImageAgreement,
1339}
1340
1341#[derive(Debug, Clone, PartialEq)]
1343pub enum RunningImageAgreement {
1344 Match {
1345 evidence: RunningImageEvidence,
1346 },
1347 Mismatch {
1348 running: RunningImageEvidence,
1349 disk: RunningImageEvidence,
1350 },
1351 Unavailable {
1352 reason: RunningImageUnavailableReason,
1353 },
1354 Unknown {
1357 tag: String,
1358 body: OrderedJsonObject,
1359 },
1360}
1361
1362#[derive(Debug, Clone, PartialEq)]
1364pub enum RunningImageEvidence {
1365 LinuxProcSha256 {
1366 digest: String,
1367 },
1368 MacosSpawnInode {
1369 device: u64,
1370 inode: u64,
1371 },
1372 WindowsSpawnFileId {
1374 volume_serial_number: u64,
1375 file_id: [u8; 16],
1376 },
1377 Unknown {
1380 tag: String,
1381 body: OrderedJsonObject,
1382 },
1383}
1384
1385open_string_enum! {
1386 RunningImageUnavailableReason {
1388 NotRunning => "not_running",
1389 NotYetMeasured => "not_yet_measured",
1390 UnsupportedPlatform => "unsupported_platform",
1391 RunningExecutableUnreadable => "running_executable_unreadable",
1392 RunningExecutablePermissionDenied => "running_executable_permission_denied",
1393 ProcessHidden => "process_hidden",
1394 SpawnedPathUnreadable => "spawned_path_unreadable",
1395 HashFailed => "hash_failed",
1396 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
1397 }
1398}
1399
1400#[derive(Debug, Clone, PartialEq)]
1406pub enum SupervisorRouteConsumer {
1407 Reserved {
1408 module_id: String,
1409 },
1410 Direct {
1411 connection_id: u64,
1412 },
1413 Unknown {
1416 tag: String,
1417 body: OrderedJsonObject,
1418 },
1419}
1420
1421#[derive(Debug, Clone, PartialEq)]
1428pub enum StderrCaptureState {
1429 Captured,
1432 Incomplete { reason: String },
1434 NotCaptured { reason: String },
1436 Unknown {
1439 tag: String,
1440 body: OrderedJsonObject,
1441 },
1442}
1443
1444#[derive(Debug, Clone, PartialEq)]
1445pub enum StderrTailEntry {
1446 Line {
1447 text: String,
1448 truncated: bool,
1453 at_ms: Option<u64>,
1457 },
1458 ProcessStart,
1463 Unknown {
1466 tag: String,
1467 body: OrderedJsonObject,
1468 },
1469}
1470
1471#[derive(Debug, Serialize, Deserialize)]
1472#[serde(tag = "status", rename_all = "snake_case")]
1473enum ModuleDeclaredProvenanceWire {
1474 Reported { build: ManifestProvenance },
1475 Unverifiable,
1476}
1477
1478#[derive(Debug, Serialize, Deserialize)]
1479#[serde(tag = "status", rename_all = "snake_case")]
1480enum RunningImageAgreementWire {
1481 Match {
1482 evidence: RunningImageEvidence,
1483 },
1484 Mismatch {
1485 running: RunningImageEvidence,
1486 disk: RunningImageEvidence,
1487 },
1488 Unavailable {
1489 reason: RunningImageUnavailableReason,
1490 },
1491}
1492
1493#[derive(Debug, Serialize, Deserialize)]
1494#[serde(tag = "status", rename_all = "snake_case")]
1495enum ReloadPathAgreementWire {
1496 Match,
1497 Mismatch {
1498 configured: PathBuf,
1499 spawned_from: PathBuf,
1500 },
1501 Unavailable {
1502 reason: ReloadPathUnavailableReason,
1503 },
1504}
1505
1506#[derive(Debug, Serialize, Deserialize)]
1507#[serde(tag = "status", rename_all = "snake_case")]
1508enum LaunchSpecAgreementWire {
1509 Match,
1510 Mismatch,
1511 Unavailable { reason: LaunchSpecUnavailableReason },
1512}
1513
1514#[derive(Debug, Serialize, Deserialize)]
1515#[serde(tag = "method", rename_all = "snake_case")]
1516enum RunningImageEvidenceWire {
1517 LinuxProcSha256 {
1518 digest: String,
1519 },
1520 MacosSpawnInode {
1521 device: u64,
1522 inode: u64,
1523 },
1524 WindowsSpawnFileId {
1525 volume_serial_number: u64,
1526 file_id: [u8; 16],
1527 },
1528}
1529
1530#[derive(Debug, Serialize, Deserialize)]
1531#[serde(tag = "kind", rename_all = "snake_case")]
1532enum SupervisorRouteConsumerWire {
1533 Reserved { module_id: String },
1534 Direct { connection_id: u64 },
1535}
1536
1537#[derive(Debug, Serialize, Deserialize)]
1538#[serde(tag = "state", rename_all = "snake_case")]
1539enum StderrCaptureStateWire {
1540 Captured,
1541 Incomplete { reason: String },
1542 NotCaptured { reason: String },
1543}
1544
1545#[derive(Debug, Serialize, Deserialize)]
1546#[serde(tag = "status", rename_all = "snake_case")]
1547enum ChildResourceUsageWire {
1548 Measured(ChildResourceReading),
1549 Unavailable {
1550 reason: ChildResourceUnavailableReason,
1551 },
1552}
1553
1554#[derive(Debug, Serialize, Deserialize)]
1555#[serde(tag = "kind", rename_all = "snake_case")]
1556enum StderrTailEntryWire {
1557 Line {
1558 text: String,
1559 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1560 truncated: bool,
1561 #[serde(default, skip_serializing_if = "Option::is_none")]
1564 at_ms: Option<u64>,
1565 },
1566 ProcessStart,
1567}
1568
1569#[derive(Debug, Clone, PartialEq)]
1571pub enum OrderedJsonValue {
1572 Null,
1573 Bool(bool),
1574 Number(serde_json::Number),
1575 String(String),
1576 Array(Vec<Self>),
1577 Object(OrderedJsonObject),
1578}
1579
1580#[derive(Debug, Clone, PartialEq)]
1582pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1583
1584impl OrderedJsonObject {
1585 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1587 &self.0
1588 }
1589
1590 fn into_value(self) -> serde_json::Value {
1591 serde_json::Value::Object(
1592 self.0
1593 .into_iter()
1594 .map(|(key, value)| (key, value.into_value()))
1595 .collect(),
1596 )
1597 }
1598}
1599
1600impl OrderedJsonValue {
1601 fn into_value(self) -> serde_json::Value {
1602 match self {
1603 Self::Null => serde_json::Value::Null,
1604 Self::Bool(value) => serde_json::Value::Bool(value),
1605 Self::Number(value) => serde_json::Value::Number(value),
1606 Self::String(value) => serde_json::Value::String(value),
1607 Self::Array(values) => {
1608 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1609 }
1610 Self::Object(value) => value.into_value(),
1611 }
1612 }
1613}
1614
1615impl Serialize for OrderedJsonValue {
1616 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1617 where
1618 S: Serializer,
1619 {
1620 match self {
1621 Self::Null => serializer.serialize_unit(),
1622 Self::Bool(value) => serializer.serialize_bool(*value),
1623 Self::Number(value) => value.serialize(serializer),
1624 Self::String(value) => serializer.serialize_str(value),
1625 Self::Array(values) => values.serialize(serializer),
1626 Self::Object(value) => value.serialize(serializer),
1627 }
1628 }
1629}
1630
1631impl<'de> Deserialize<'de> for OrderedJsonValue {
1632 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1633 where
1634 D: Deserializer<'de>,
1635 {
1636 struct OrderedValueVisitor;
1637
1638 impl<'de> Visitor<'de> for OrderedValueVisitor {
1639 type Value = OrderedJsonValue;
1640
1641 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1642 formatter.write_str("a JSON value with ordered object members")
1643 }
1644
1645 fn visit_unit<E>(self) -> Result<Self::Value, E>
1646 where
1647 E: serde::de::Error,
1648 {
1649 Ok(OrderedJsonValue::Null)
1650 }
1651
1652 fn visit_none<E>(self) -> Result<Self::Value, E>
1653 where
1654 E: serde::de::Error,
1655 {
1656 Ok(OrderedJsonValue::Null)
1657 }
1658
1659 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1660 where
1661 D: Deserializer<'de>,
1662 {
1663 OrderedJsonValue::deserialize(deserializer)
1664 }
1665
1666 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1667 where
1668 E: serde::de::Error,
1669 {
1670 Ok(OrderedJsonValue::Bool(value))
1671 }
1672
1673 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1674 where
1675 E: serde::de::Error,
1676 {
1677 Ok(OrderedJsonValue::Number(value.into()))
1678 }
1679
1680 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1681 where
1682 E: serde::de::Error,
1683 {
1684 Ok(OrderedJsonValue::Number(value.into()))
1685 }
1686
1687 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1688 where
1689 E: serde::de::Error,
1690 {
1691 serde_json::Number::from_f64(value)
1692 .map(OrderedJsonValue::Number)
1693 .ok_or_else(|| E::custom("non-finite JSON number"))
1694 }
1695
1696 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1697 where
1698 E: serde::de::Error,
1699 {
1700 Ok(OrderedJsonValue::String(value.to_owned()))
1701 }
1702
1703 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1704 where
1705 E: serde::de::Error,
1706 {
1707 Ok(OrderedJsonValue::String(value))
1708 }
1709
1710 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1711 where
1712 A: SeqAccess<'de>,
1713 {
1714 let mut values = Vec::new();
1715 while let Some(value) = sequence.next_element()? {
1716 values.push(value);
1717 }
1718 Ok(OrderedJsonValue::Array(values))
1719 }
1720
1721 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1722 where
1723 A: MapAccess<'de>,
1724 {
1725 let mut entries = Vec::new();
1726 while let Some((key, value)) = map.next_entry()? {
1727 entries.push((key, value));
1728 }
1729 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1730 }
1731 }
1732
1733 deserializer.deserialize_any(OrderedValueVisitor)
1734 }
1735}
1736
1737impl Serialize for OrderedJsonObject {
1738 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1739 where
1740 S: Serializer,
1741 {
1742 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1743 for (key, value) in &self.0 {
1744 map.serialize_entry(key, value)?;
1745 }
1746 map.end()
1747 }
1748}
1749
1750impl<'de> Deserialize<'de> for OrderedJsonObject {
1751 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1752 where
1753 D: Deserializer<'de>,
1754 {
1755 struct OrderedObjectVisitor;
1756
1757 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1758 type Value = OrderedJsonObject;
1759
1760 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1761 formatter.write_str("an object with ordered JSON members")
1762 }
1763
1764 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1765 where
1766 A: MapAccess<'de>,
1767 {
1768 let mut entries = Vec::new();
1769 while let Some((key, value)) = map.next_entry()? {
1770 entries.push((key, value));
1771 }
1772 Ok(OrderedJsonObject(entries))
1773 }
1774 }
1775
1776 deserializer.deserialize_map(OrderedObjectVisitor)
1777 }
1778}
1779
1780fn read_tagged<'de, D>(
1781 deserializer: D,
1782 field: &'static str,
1783) -> Result<(String, OrderedJsonObject), D::Error>
1784where
1785 D: Deserializer<'de>,
1786{
1787 let body = OrderedJsonObject::deserialize(deserializer)?;
1788 let mut tag = None;
1789 for (key, value) in body.as_entries() {
1790 if key != field {
1791 continue;
1792 }
1793 if tag.is_some() {
1794 return Err(D::Error::custom(format!(
1795 "tagged object has duplicate `{field}` field"
1796 )));
1797 }
1798 let OrderedJsonValue::String(value) = value else {
1799 return Err(D::Error::custom(format!(
1800 "tagged object has no string `{field}` field"
1801 )));
1802 };
1803 tag = Some(value);
1804 }
1805 let Some(tag) = tag else {
1806 return Err(D::Error::custom(format!(
1807 "tagged object has no string `{field}` field"
1808 )));
1809 };
1810 Ok((tag.to_string(), body))
1811}
1812
1813fn read_ordered_tagged(
1814 value: OrderedJsonValue,
1815 field: &'static str,
1816) -> Result<(String, OrderedJsonObject), String> {
1817 let OrderedJsonValue::Object(body) = value else {
1818 return Err(format!("expected tagged object with `{field}` field"));
1819 };
1820 let mut tag = None;
1821 for (key, value) in body.as_entries() {
1822 if key != field {
1823 continue;
1824 }
1825 if tag.is_some() {
1826 return Err(format!("tagged object has duplicate `{field}` field"));
1827 }
1828 let OrderedJsonValue::String(value) = value else {
1829 return Err(format!("tagged object has no string `{field}` field"));
1830 };
1831 tag = Some(value);
1832 }
1833 let Some(tag) = tag else {
1834 return Err(format!("tagged object has no string `{field}` field"));
1835 };
1836 Ok((tag.to_string(), body))
1837}
1838
1839fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1840 body.as_entries()
1841 .iter()
1842 .find_map(|(key, value)| (key == field).then_some(value))
1843}
1844
1845fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1846 match ordered_field(body, field) {
1847 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1848 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1849 None => Err(format!("tagged object has no `{field}` field")),
1850 }
1851}
1852
1853fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1854 let (tag, body) = read_ordered_tagged(value, "method")?;
1855 match tag.as_str() {
1856 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1857 digest: ordered_string(&body, "digest")?,
1858 }),
1859 "macos_spawn_inode" => {
1860 let device = ordered_field(&body, "device")
1861 .and_then(|value| match value {
1862 OrderedJsonValue::Number(number) => number.as_u64(),
1863 _ => None,
1864 })
1865 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1866 let inode = ordered_field(&body, "inode")
1867 .and_then(|value| match value {
1868 OrderedJsonValue::Number(number) => number.as_u64(),
1869 _ => None,
1870 })
1871 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1872 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1873 }
1874 "windows_spawn_file_id" => {
1875 let wire: RunningImageEvidenceWire = serde_json::from_value(
1876 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1877 )
1878 .map_err(|error| error.to_string())?;
1879 match wire {
1880 RunningImageEvidenceWire::WindowsSpawnFileId {
1881 volume_serial_number,
1882 file_id,
1883 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1884 volume_serial_number,
1885 file_id,
1886 }),
1887 _ => unreachable!(),
1888 }
1889 }
1890 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1891 }
1892}
1893
1894impl Serialize for ModuleDeclaredProvenance {
1895 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1896 where
1897 S: Serializer,
1898 {
1899 match self {
1900 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1901 build: build.clone(),
1902 }
1903 .serialize(serializer),
1904 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1905 Self::Unknown { body, .. } => body.serialize(serializer),
1906 }
1907 }
1908}
1909
1910impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1911 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1912 where
1913 D: serde::Deserializer<'de>,
1914 {
1915 let (tag, value) = read_tagged(deserializer, "status")?;
1916 match tag.as_str() {
1917 "reported" => match serde_json::from_value(value.into_value())
1918 .map_err(D::Error::custom)?
1919 {
1920 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1921 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1922 },
1923 "unverifiable" => {
1924 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1925 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1926 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1927 }
1928 }
1929 _ => Ok(Self::Unknown { tag, body: value }),
1930 }
1931 }
1932}
1933
1934impl Serialize for RunningImageAgreement {
1935 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1936 where
1937 S: Serializer,
1938 {
1939 match self {
1940 Self::Match { evidence } => RunningImageAgreementWire::Match {
1941 evidence: evidence.clone(),
1942 }
1943 .serialize(serializer),
1944 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1945 running: running.clone(),
1946 disk: disk.clone(),
1947 }
1948 .serialize(serializer),
1949 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1950 reason: reason.clone(),
1951 }
1952 .serialize(serializer),
1953 Self::Unknown { body, .. } => body.serialize(serializer),
1954 }
1955 }
1956}
1957
1958impl Serialize for ReloadPathAgreement {
1959 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1960 where
1961 S: Serializer,
1962 {
1963 match self {
1964 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1965 Self::Mismatch {
1966 configured,
1967 spawned_from,
1968 } => ReloadPathAgreementWire::Mismatch {
1969 configured: configured.clone(),
1970 spawned_from: spawned_from.clone(),
1971 }
1972 .serialize(serializer),
1973 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1974 reason: reason.clone(),
1975 }
1976 .serialize(serializer),
1977 Self::Unknown { body, .. } => body.serialize(serializer),
1978 }
1979 }
1980}
1981
1982impl Serialize for LaunchSpecAgreement {
1983 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1984 where
1985 S: Serializer,
1986 {
1987 match self {
1988 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1989 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1990 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1991 reason: reason.clone(),
1992 }
1993 .serialize(serializer),
1994 Self::Unknown { body, .. } => body.serialize(serializer),
1995 }
1996 }
1997}
1998
1999impl<'de> Deserialize<'de> for LaunchSpecAgreement {
2000 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2001 where
2002 D: Deserializer<'de>,
2003 {
2004 let (tag, body) = read_tagged(deserializer, "status")?;
2005 match tag.as_str() {
2006 "match" => Ok(Self::Match),
2007 "mismatch" => Ok(Self::Mismatch),
2008 "unavailable" => match serde_json::from_value(body.into_value())
2009 .map_err(D::Error::custom)?
2010 {
2011 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
2012 _ => unreachable!(),
2013 },
2014 _ => Ok(Self::Unknown { tag, body }),
2015 }
2016 }
2017}
2018
2019impl<'de> Deserialize<'de> for ReloadPathAgreement {
2020 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2021 where
2022 D: Deserializer<'de>,
2023 {
2024 let (tag, body) = read_tagged(deserializer, "status")?;
2025 match tag.as_str() {
2026 "match" => Ok(Self::Match),
2027 "mismatch" => {
2028 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2029 ReloadPathAgreementWire::Mismatch {
2030 configured,
2031 spawned_from,
2032 } => Ok(Self::Mismatch {
2033 configured,
2034 spawned_from,
2035 }),
2036 _ => unreachable!(),
2037 }
2038 }
2039 "unavailable" => match serde_json::from_value(body.into_value())
2040 .map_err(D::Error::custom)?
2041 {
2042 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
2043 _ => unreachable!(),
2044 },
2045 _ => Ok(Self::Unknown { tag, body }),
2046 }
2047 }
2048}
2049
2050impl<'de> Deserialize<'de> for RunningImageAgreement {
2051 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2052 where
2053 D: serde::Deserializer<'de>,
2054 {
2055 let (tag, value) = read_tagged(deserializer, "status")?;
2056 match tag.as_str() {
2057 "match" => Ok(Self::Match {
2058 evidence: decode_running_image_evidence(
2059 ordered_field(&value, "evidence")
2060 .cloned()
2061 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
2062 )
2063 .map_err(D::Error::custom)?,
2064 }),
2065 "mismatch" => Ok(Self::Mismatch {
2066 running: decode_running_image_evidence(
2067 ordered_field(&value, "running")
2068 .cloned()
2069 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
2070 )
2071 .map_err(D::Error::custom)?,
2072 disk: decode_running_image_evidence(
2073 ordered_field(&value, "disk")
2074 .cloned()
2075 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
2076 )
2077 .map_err(D::Error::custom)?,
2078 }),
2079 "unavailable" => Ok(Self::Unavailable {
2080 reason: serde_json::from_value(
2081 ordered_field(&value, "reason")
2082 .cloned()
2083 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
2084 .into_value(),
2085 )
2086 .map_err(D::Error::custom)?,
2087 }),
2088 _ => Ok(Self::Unknown { tag, body: value }),
2089 }
2090 }
2091}
2092
2093impl Serialize for ChildResourceUsage {
2094 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2095 where
2096 S: Serializer,
2097 {
2098 match self {
2099 Self::Measured(reading) => {
2100 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
2101 }
2102 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
2103 reason: reason.clone(),
2104 }
2105 .serialize(serializer),
2106 Self::Unknown { body, .. } => body.serialize(serializer),
2107 }
2108 }
2109}
2110
2111impl<'de> Deserialize<'de> for ChildResourceUsage {
2112 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2113 where
2114 D: Deserializer<'de>,
2115 {
2116 let (tag, body) = read_tagged(deserializer, "status")?;
2117 match tag.as_str() {
2118 "measured" | "unavailable" => {
2119 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2120 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
2121 ChildResourceUsageWire::Unavailable { reason } => {
2122 Ok(Self::Unavailable { reason })
2123 }
2124 }
2125 }
2126 _ => Ok(Self::Unknown { tag, body }),
2127 }
2128 }
2129}
2130
2131impl Serialize for RunningImageEvidence {
2132 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2133 where
2134 S: Serializer,
2135 {
2136 match self {
2137 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
2138 digest: digest.clone(),
2139 }
2140 .serialize(serializer),
2141 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
2142 device: *device,
2143 inode: *inode,
2144 }
2145 .serialize(serializer),
2146 Self::WindowsSpawnFileId {
2147 volume_serial_number,
2148 file_id,
2149 } => RunningImageEvidenceWire::WindowsSpawnFileId {
2150 volume_serial_number: *volume_serial_number,
2151 file_id: *file_id,
2152 }
2153 .serialize(serializer),
2154 Self::Unknown { body, .. } => body.serialize(serializer),
2155 }
2156 }
2157}
2158
2159impl<'de> Deserialize<'de> for RunningImageEvidence {
2160 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2161 where
2162 D: serde::Deserializer<'de>,
2163 {
2164 let (tag, value) = read_tagged(deserializer, "method")?;
2165 match tag.as_str() {
2166 "linux_proc_sha256" => {
2167 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2168 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
2169 Ok(Self::LinuxProcSha256 { digest })
2170 }
2171 _ => unreachable!(),
2172 }
2173 }
2174 "macos_spawn_inode" => {
2175 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2176 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
2177 Ok(Self::MacosSpawnInode { device, inode })
2178 }
2179 _ => unreachable!(),
2180 }
2181 }
2182 "windows_spawn_file_id" => {
2183 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2184 RunningImageEvidenceWire::WindowsSpawnFileId {
2185 volume_serial_number,
2186 file_id,
2187 } => Ok(Self::WindowsSpawnFileId {
2188 volume_serial_number,
2189 file_id,
2190 }),
2191 _ => unreachable!(),
2192 }
2193 }
2194 _ => Ok(Self::Unknown { tag, body: value }),
2195 }
2196 }
2197}
2198
2199impl Serialize for SupervisorRouteConsumer {
2200 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2201 where
2202 S: Serializer,
2203 {
2204 match self {
2205 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
2206 module_id: module_id.clone(),
2207 }
2208 .serialize(serializer),
2209 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
2210 connection_id: *connection_id,
2211 }
2212 .serialize(serializer),
2213 Self::Unknown { body, .. } => body.serialize(serializer),
2214 }
2215 }
2216}
2217
2218impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
2219 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2220 where
2221 D: serde::Deserializer<'de>,
2222 {
2223 let (tag, value) = read_tagged(deserializer, "kind")?;
2224 match tag.as_str() {
2225 "reserved" => {
2226 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2227 SupervisorRouteConsumerWire::Reserved { module_id } => {
2228 Ok(Self::Reserved { module_id })
2229 }
2230 _ => unreachable!(),
2231 }
2232 }
2233 "direct" => {
2234 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2235 SupervisorRouteConsumerWire::Direct { connection_id } => {
2236 Ok(Self::Direct { connection_id })
2237 }
2238 _ => unreachable!(),
2239 }
2240 }
2241 _ => Ok(Self::Unknown { tag, body: value }),
2242 }
2243 }
2244}
2245
2246impl Serialize for StderrCaptureState {
2247 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2248 where
2249 S: Serializer,
2250 {
2251 match self {
2252 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
2253 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
2254 reason: reason.clone(),
2255 }
2256 .serialize(serializer),
2257 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
2258 reason: reason.clone(),
2259 }
2260 .serialize(serializer),
2261 Self::Unknown { body, .. } => body.serialize(serializer),
2262 }
2263 }
2264}
2265
2266impl<'de> Deserialize<'de> for StderrCaptureState {
2267 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2268 where
2269 D: serde::Deserializer<'de>,
2270 {
2271 let (tag, value) = read_tagged(deserializer, "state")?;
2272 match tag.as_str() {
2273 "captured" => {
2274 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2275 StderrCaptureStateWire::Captured => Ok(Self::Captured),
2276 _ => unreachable!(),
2277 }
2278 }
2279 "incomplete" => match serde_json::from_value(value.into_value())
2280 .map_err(D::Error::custom)?
2281 {
2282 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
2283 _ => unreachable!(),
2284 },
2285 "not_captured" => match serde_json::from_value(value.into_value())
2286 .map_err(D::Error::custom)?
2287 {
2288 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
2289 _ => unreachable!(),
2290 },
2291 _ => Ok(Self::Unknown { tag, body: value }),
2292 }
2293 }
2294}
2295
2296impl Serialize for StderrTailEntry {
2297 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2298 where
2299 S: Serializer,
2300 {
2301 match self {
2302 Self::Line {
2303 text,
2304 truncated,
2305 at_ms,
2306 } => StderrTailEntryWire::Line {
2307 text: text.clone(),
2308 truncated: *truncated,
2309 at_ms: *at_ms,
2310 }
2311 .serialize(serializer),
2312 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
2313 Self::Unknown { body, .. } => body.serialize(serializer),
2314 }
2315 }
2316}
2317
2318impl<'de> Deserialize<'de> for StderrTailEntry {
2319 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2320 where
2321 D: serde::Deserializer<'de>,
2322 {
2323 let (tag, value) = read_tagged(deserializer, "kind")?;
2324 match tag.as_str() {
2325 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2326 StderrTailEntryWire::Line {
2327 text,
2328 truncated,
2329 at_ms,
2330 } => Ok(Self::Line {
2331 text,
2332 truncated,
2333 at_ms,
2334 }),
2335 _ => unreachable!(),
2336 },
2337 "process_start" => {
2338 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2339 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
2340 _ => unreachable!(),
2341 }
2342 }
2343 _ => Ok(Self::Unknown { tag, body: value }),
2344 }
2345 }
2346}
2347
2348fn is_zero_u64(value: &u64) -> bool {
2349 *value == 0
2350}
2351
2352fn default_true() -> bool {
2353 true
2354}
2355
2356#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2358pub struct TerminalHistory {
2359 pub daemon_started_at_ms: u64,
2361 pub entries: Vec<TerminalEntry>,
2362 #[serde(default, skip_serializing_if = "is_zero_u64")]
2365 pub dropped: u64,
2366 #[serde(default, skip_serializing_if = "is_zero_u64")]
2369 pub journal_skipped_lines: u64,
2370 #[serde(default, skip_serializing_if = "is_zero_u64")]
2372 pub journal_read_errors: u64,
2373 #[serde(default, skip_serializing_if = "is_zero_u64")]
2375 pub journal_write_failures: u64,
2376}
2377
2378#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2380pub struct TerminalEntry {
2381 #[serde(default, skip_serializing_if = "Option::is_none")]
2384 pub daemon_incarnation: Option<String>,
2385 #[serde(default, skip_serializing_if = "Option::is_none")]
2386 pub exit_code: Option<i32>,
2387 #[serde(default, skip_serializing_if = "Option::is_none")]
2388 pub exit_signal: Option<i32>,
2389 pub at_ms: u64,
2390 pub disposition: TerminalDisposition,
2391 #[serde(default, skip_serializing_if = "Option::is_none")]
2395 pub exit_kind: Option<TerminalExitKind>,
2396 #[serde(default, skip_serializing_if = "Option::is_none")]
2403 pub disposition_detail: Option<String>,
2404}
2405
2406#[derive(Debug, Clone, PartialEq, Eq)]
2411pub enum TerminalExitKind {
2412 Clean,
2413 Crash,
2414 DeliberateSeverance,
2415 Unknown(String),
2416}
2417
2418impl TerminalExitKind {
2419 fn wire_name(&self) -> &str {
2420 match self {
2421 Self::Clean => "clean",
2422 Self::Crash => "crash",
2423 Self::DeliberateSeverance => "deliberate_severance",
2424 Self::Unknown(value) => value,
2425 }
2426 }
2427}
2428
2429impl Serialize for TerminalExitKind {
2430 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2431 where
2432 S: serde::Serializer,
2433 {
2434 serializer.serialize_str(self.wire_name())
2435 }
2436}
2437
2438impl<'de> Deserialize<'de> for TerminalExitKind {
2439 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2440 where
2441 D: serde::Deserializer<'de>,
2442 {
2443 let value = String::deserialize(deserializer)?;
2444 Ok(match value.as_str() {
2445 "clean" => Self::Clean,
2446 "crash" => Self::Crash,
2447 "deliberate_severance" => Self::DeliberateSeverance,
2448 _ => Self::Unknown(value),
2449 })
2450 }
2451}
2452
2453open_string_enum! {
2454 TerminalDisposition {
2456 Stopped => "stopped",
2457 Disabled => "disabled",
2458 Failed => "failed",
2459 Restarting => "restarting",
2460 DaemonShutdown => "daemon_shutdown",
2465 }
2466}
2467
2468#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2469#[serde(rename_all = "snake_case")]
2470pub enum PollKind {
2471 Status,
2472 Liveness,
2473}
2474
2475#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2487#[non_exhaustive]
2488pub struct CatalogEntry {
2489 pub module_id: String,
2490 #[serde(default, skip_serializing_if = "Option::is_none")]
2492 pub display_name: Option<String>,
2493 #[serde(default = "default_true")]
2504 pub ready: bool,
2505 #[serde(default, skip_serializing_if = "Option::is_none")]
2509 pub not_ready: Option<NotReadyReason>,
2510 #[serde(default, skip_serializing_if = "Option::is_none")]
2531 pub module_version: Option<String>,
2532 #[serde(default, skip_serializing_if = "Option::is_none")]
2535 pub provenance: Option<ManifestProvenance>,
2536 pub roles: Vec<ProviderRole>,
2537 pub control_ops: Vec<String>,
2538 #[serde(default, skip_serializing_if = "Option::is_none")]
2543 pub capabilities: Option<CapabilityDeclarations>,
2544 #[serde(default, skip_serializing_if = "Option::is_none")]
2547 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2548 #[serde(default, skip_serializing_if = "Option::is_none")]
2552 pub events: Option<Vec<EventDeclaration>>,
2553 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2556 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2557 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2560 pub operation_payload: BTreeMap<String, OperationPayload>,
2561 #[serde(default, skip_serializing_if = "Option::is_none")]
2567 pub flow_operations: Option<Vec<String>>,
2568 #[serde(default, skip_serializing_if = "Option::is_none")]
2570 pub operation_deferral: Option<BTreeMap<String, bool>>,
2571 #[serde(default, skip_serializing_if = "Option::is_none")]
2577 pub confirm_operations: Option<Vec<String>>,
2578 #[serde(default, skip_serializing_if = "Option::is_none")]
2581 pub rich_ui: Option<RichUiDescriptor>,
2582 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2585 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2586 #[serde(default, skip_serializing_if = "is_false")]
2591 pub nonce_verified: bool,
2592 #[serde(default, skip_serializing_if = "Option::is_none")]
2595 pub incarnation: Option<String>,
2596 #[serde(
2597 default,
2598 skip_serializing_if = "Option::is_none",
2599 deserialize_with = "deserialize_optional_attestation_integer"
2600 )]
2601 pub spawn: Option<u64>,
2602 #[serde(default, skip_serializing_if = "Option::is_none")]
2603 pub first_party: Option<bool>,
2604 #[serde(default, skip_serializing_if = "Option::is_none")]
2605 pub origin: Option<CatalogOrigin>,
2606 #[serde(default, skip_serializing_if = "Option::is_none")]
2607 pub requested_declarations_digest: Option<String>,
2608 #[serde(default, skip_serializing_if = "Option::is_none")]
2609 pub approved_declarations_digest: Option<String>,
2610 #[serde(default, skip_serializing_if = "Option::is_none")]
2613 pub approved_declarations: Option<ProviderDeclarations>,
2614 #[serde(default, skip_serializing_if = "Option::is_none")]
2615 pub requested_declarations: Option<ProviderDeclarations>,
2616}
2617
2618impl CatalogEntry {
2619 #[must_use]
2621 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2622 self.display_name = display_name;
2623 self
2624 }
2625
2626 #[must_use]
2628 pub fn new(
2629 module_id: impl Into<String>,
2630 roles: Vec<ProviderRole>,
2631 control_ops: Vec<String>,
2632 ) -> Self {
2633 Self {
2634 module_id: module_id.into(),
2635 ready: default_true(),
2636 display_name: None,
2637 not_ready: None,
2638 module_version: None,
2639 provenance: None,
2640 roles,
2641 control_ops,
2642 capabilities: None,
2643 self_signals: None,
2644 events: None,
2645 operation_delivery: BTreeMap::new(),
2646 operation_payload: BTreeMap::new(),
2647 flow_operations: None,
2648 operation_deferral: None,
2649 confirm_operations: None,
2650 rich_ui: None,
2651 role_declarations: BTreeMap::new(),
2652 nonce_verified: false,
2653 incarnation: None,
2654 spawn: None,
2655 first_party: None,
2656 origin: None,
2657 requested_declarations_digest: None,
2658 approved_declarations_digest: None,
2659 approved_declarations: None,
2660 requested_declarations: None,
2661 }
2662 }
2663
2664 #[must_use]
2666 pub fn with_operation_payload(
2667 mut self,
2668 operation_payload: BTreeMap<String, OperationPayload>,
2669 ) -> Self {
2670 self.operation_payload = operation_payload;
2671 self
2672 }
2673
2674 #[must_use]
2677 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2678 self.flow_operations = flow_operations;
2679 self
2680 }
2681
2682 #[must_use]
2684 pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
2685 self.operation_deferral = operations;
2686 self
2687 }
2688
2689 #[must_use]
2692 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2693 self.confirm_operations = confirm_operations;
2694 self
2695 }
2696
2697 #[must_use]
2699 pub fn with_ready(mut self, ready: bool) -> Self {
2700 self.ready = ready;
2701 self
2702 }
2703
2704 #[must_use]
2706 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2707 self.not_ready = not_ready;
2708 self
2709 }
2710
2711 #[must_use]
2713 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2714 self.module_version = module_version;
2715 self
2716 }
2717
2718 #[must_use]
2720 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2721 self.provenance = provenance;
2722 self
2723 }
2724
2725 #[must_use]
2727 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2728 self.capabilities = capabilities;
2729 self
2730 }
2731
2732 #[must_use]
2734 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2735 self.self_signals = self_signals;
2736 self
2737 }
2738
2739 #[must_use]
2741 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2742 self.events = events;
2743 self
2744 }
2745
2746 #[must_use]
2749 pub fn with_operation_delivery(
2750 mut self,
2751 operation_delivery: BTreeMap<String, OperationDelivery>,
2752 ) -> Self {
2753 self.operation_delivery = operation_delivery;
2754 self
2755 }
2756
2757 #[must_use]
2759 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2760 self.rich_ui = rich_ui;
2761 self
2762 }
2763
2764 #[must_use]
2766 pub fn with_role_declarations(
2767 mut self,
2768 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2769 ) -> Self {
2770 self.role_declarations = role_declarations;
2771 self
2772 }
2773
2774 #[must_use]
2776 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2777 self.nonce_verified = nonce_verified;
2778 self
2779 }
2780}
2781
2782fn is_false(value: &bool) -> bool {
2783 !value
2784}
2785
2786#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2788pub struct NotReadyReason {
2789 pub reason: String,
2794 #[serde(default, skip_serializing_if = "Option::is_none")]
2797 pub capability: Option<String>,
2798}
2799
2800impl NotReadyReason {
2801 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2802 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2803}
2804
2805#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2806pub struct CapabilityRequirementStatus {
2807 pub consumer: String,
2808 pub capability: String,
2809 pub need: String,
2810 pub verdict: String,
2811 pub episode_seq: u64,
2812 pub config_satisfiable: bool,
2813 pub runtime_available: bool,
2814 pub detail: String,
2815}
2816
2817#[non_exhaustive]
2822#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2823#[serde(rename_all = "snake_case")]
2824pub enum PendingModuleApply {
2825 NextSupervision,
2826 WithNextLaunchOrHealthChange,
2827 DaemonRestart,
2828 ConfigGate,
2829 #[serde(other)]
2830 Other,
2831}
2832
2833#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2835pub struct SupervisorPendingField {
2836 pub field: String,
2837 pub applies: PendingModuleApply,
2838 #[serde(default, skip_serializing_if = "Option::is_none")]
2839 pub value: Option<serde_json::Value>,
2840}
2841
2842#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2843pub struct SupervisorPendingModule {
2844 pub module_id: String,
2845 pub fields: Vec<SupervisorPendingField>,
2846}
2847
2848#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2853pub struct SupervisorLiveChange {
2854 pub module_id: String,
2855 pub fields: Vec<String>,
2856}
2857
2858#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2859pub struct SupervisorRescanResult {
2860 pub added: Vec<String>,
2861 pub removed: Vec<String>,
2862 pub changed_pending_reload: Vec<String>,
2863 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2865 pub changed_pending: Vec<SupervisorPendingModule>,
2866 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2868 pub changed_live: Vec<SupervisorLiveChange>,
2869 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2882 pub enabled_changes: Vec<String>,
2883 pub unchanged: u32,
2884 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2892 pub preview: bool,
2893 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2911 pub restart_required: Vec<String>,
2912 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2916 pub capability_warnings: Vec<String>,
2917 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2923 pub module_actions: Vec<RescanModuleAction>,
2924 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2928 pub earlier_pending: Vec<String>,
2929 #[serde(default, skip_serializing_if = "Option::is_none")]
2932 pub expect: Option<RescanExpect>,
2933}
2934
2935#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2951#[serde(rename_all = "snake_case")]
2952pub enum ModuleProtocol {
2953 #[default]
2957 Subc,
2958 None,
2967}
2968
2969#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2981#[non_exhaustive]
2982pub struct SupervisorEntry {
2983 #[serde(default, skip_serializing_if = "Option::is_none")]
2985 pub script: Option<ScriptModuleStatus>,
2986 #[serde(default, skip_serializing_if = "Option::is_none")]
2989 pub waiting_for_previous_pid: Option<u32>,
2990 #[serde(default, skip_serializing_if = "Option::is_none")]
2993 pub waiting_for_previous_detail: Option<String>,
2994 pub module_id: String,
2995 pub state: String,
2996 #[serde(default, skip_serializing_if = "Option::is_none")]
2998 pub accepting_drain: Option<bool>,
2999 #[serde(default, skip_serializing_if = "Option::is_none")]
3003 pub admission_refused: Option<String>,
3004 #[serde(default, skip_serializing_if = "Option::is_none")]
3008 pub next_retry_at_ms: Option<u64>,
3009 pub enabled: bool,
3010 #[serde(default, skip_serializing_if = "Option::is_none")]
3013 pub configured_enabled: Option<bool>,
3014 pub live: bool,
3024 #[serde(default)]
3028 pub protocol: ModuleProtocol,
3029 #[serde(default, skip_serializing_if = "Option::is_none")]
3032 pub launch_nonce_env: Option<bool>,
3033 #[serde(default, skip_serializing_if = "Option::is_none")]
3039 pub launch_nonce_source: Option<String>,
3040 pub health: SupervisorHealthStatus,
3041 #[serde(default, skip_serializing_if = "Option::is_none")]
3044 pub pending_reload: Option<PendingReloadVerdict>,
3045 #[serde(default)]
3051 pub last_probe_ms: Option<u64>,
3052 #[serde(default, skip_serializing_if = "Option::is_none")]
3056 pub last_exit_code: Option<i32>,
3057 #[serde(default, skip_serializing_if = "Option::is_none")]
3061 pub last_exit_signal: Option<i32>,
3062 #[serde(default, skip_serializing_if = "Option::is_none")]
3066 pub last_exit_ms: Option<u64>,
3067 #[serde(default, skip_serializing_if = "Option::is_none")]
3070 pub last_exit_kind: Option<TerminalExitKind>,
3071 #[serde(default, skip_serializing_if = "Option::is_none")]
3088 pub restart_count: Option<u32>,
3089 #[serde(default, skip_serializing_if = "Option::is_none")]
3092 pub max_restarts: Option<u32>,
3093 #[serde(default, skip_serializing_if = "Option::is_none")]
3096 pub lifetime_restarts: Option<u32>,
3097 #[serde(default, skip_serializing_if = "Option::is_none")]
3101 pub spawn_generation: Option<u64>,
3102 #[serde(default, skip_serializing_if = "Option::is_none")]
3112 pub restart_window_secs: Option<u64>,
3113 #[serde(default, skip_serializing_if = "Option::is_none")]
3117 pub drain_timeout_ms: Option<u64>,
3118 #[serde(default, skip_serializing_if = "Option::is_none")]
3121 pub restart_backoff_ms: Option<u64>,
3122 #[serde(default, skip_serializing_if = "Option::is_none")]
3125 pub restart_max_backoff_ms: Option<u64>,
3126 #[serde(default, skip_serializing_if = "Option::is_none")]
3139 pub resources: Option<ChildResourceUsage>,
3140 #[serde(default, skip_serializing_if = "Option::is_none")]
3142 pub tree: Option<TreeReading>,
3143 #[serde(default, skip_serializing_if = "Option::is_none")]
3149 pub tree_unavailable: Option<String>,
3150 #[serde(default, skip_serializing_if = "Option::is_none")]
3152 pub cpu_last_hour: Option<CpuLastHour>,
3153 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3155 pub pending: Vec<SupervisorPendingField>,
3156}
3157
3158impl SupervisorEntry {
3159 #[must_use]
3160 pub fn with_script(mut self, script: Option<ScriptModuleStatus>) -> Self {
3161 self.script = script;
3162 self
3163 }
3164 #[must_use]
3166 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3167 self.next_retry_at_ms = next_retry_at_ms;
3168 self
3169 }
3170
3171 #[must_use]
3173 pub fn new(
3174 module_id: impl Into<String>,
3175 state: impl Into<String>,
3176 enabled: bool,
3177 live: bool,
3178 health: SupervisorHealthStatus,
3179 ) -> Self {
3180 Self {
3181 module_id: module_id.into(),
3182 script: None,
3183 state: state.into(),
3184 admission_refused: None,
3185 next_retry_at_ms: None,
3186 waiting_for_previous_pid: None,
3187 waiting_for_previous_detail: None,
3188 accepting_drain: None,
3189 enabled,
3190 configured_enabled: None,
3191 live,
3192 protocol: ModuleProtocol::default(),
3193 launch_nonce_env: None,
3194 launch_nonce_source: None,
3195 health,
3196 pending_reload: None,
3197 last_probe_ms: None,
3198 last_exit_code: None,
3199 last_exit_signal: None,
3200 last_exit_ms: None,
3201 last_exit_kind: None,
3202 restart_count: None,
3203 max_restarts: None,
3204 lifetime_restarts: None,
3205 spawn_generation: None,
3206 restart_window_secs: None,
3207 drain_timeout_ms: None,
3208 restart_backoff_ms: None,
3209 restart_max_backoff_ms: None,
3210 resources: None,
3211 tree: None,
3212 tree_unavailable: None,
3213 cpu_last_hour: None,
3214 pending: Vec::new(),
3215 }
3216 }
3217
3218 #[must_use]
3220 pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3221 self.admission_refused = reason;
3222 self
3223 }
3224
3225 #[must_use]
3227 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3228 self.protocol = protocol;
3229 self
3230 }
3231
3232 #[must_use]
3234 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3235 self.configured_enabled = configured_enabled;
3236 self
3237 }
3238
3239 #[must_use]
3241 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3242 self.launch_nonce_env = launch_nonce_env;
3243 self
3244 }
3245
3246 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3247 self.launch_nonce_source = source;
3248 self
3249 }
3250
3251 #[must_use]
3252 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3253 self.waiting_for_previous_pid = pid;
3254 self
3255 }
3256
3257 #[must_use]
3258 pub fn with_waiting_for_previous_detail(mut self, detail: Option<String>) -> Self {
3259 self.waiting_for_previous_detail = detail;
3260 self
3261 }
3262
3263 #[must_use]
3265 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3266 self.pending_reload = pending_reload;
3267 self
3268 }
3269
3270 #[must_use]
3272 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3273 self.last_probe_ms = last_probe_ms;
3274 self
3275 }
3276
3277 #[must_use]
3279 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3280 self.last_exit_code = last_exit_code;
3281 self
3282 }
3283
3284 #[must_use]
3286 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3287 self.last_exit_signal = last_exit_signal;
3288 self
3289 }
3290
3291 #[must_use]
3293 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3294 self.last_exit_ms = last_exit_ms;
3295 self
3296 }
3297
3298 #[must_use]
3300 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3301 self.last_exit_kind = last_exit_kind;
3302 self
3303 }
3304
3305 #[must_use]
3307 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3308 self.restart_count = restart_count;
3309 self
3310 }
3311
3312 #[must_use]
3314 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3315 self.max_restarts = max_restarts;
3316 self
3317 }
3318
3319 #[must_use]
3321 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3322 self.lifetime_restarts = lifetime_restarts;
3323 self
3324 }
3325
3326 #[must_use]
3328 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3329 self.spawn_generation = spawn_generation;
3330 self
3331 }
3332
3333 #[must_use]
3335 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3336 self.restart_window_secs = restart_window_secs;
3337 self
3338 }
3339
3340 #[must_use]
3342 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3343 self.drain_timeout_ms = drain_timeout_ms;
3344 self
3345 }
3346
3347 #[must_use]
3349 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3350 self.restart_backoff_ms = restart_backoff_ms;
3351 self
3352 }
3353
3354 #[must_use]
3356 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3357 self.restart_max_backoff_ms = restart_max_backoff_ms;
3358 self
3359 }
3360
3361 #[must_use]
3363 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3364 self.resources = resources;
3365 self
3366 }
3367
3368 #[must_use]
3370 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3371 self.tree = tree;
3372 self
3373 }
3374
3375 #[must_use]
3377 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3378 self.tree_unavailable = reason;
3379 self
3380 }
3381}
3382
3383#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3385pub struct ScriptModuleStatus {
3386 pub runtime: String,
3387 pub bun_version: Option<String>,
3388 pub path: PathBuf,
3389 pub sha256: Option<String>,
3390 pub size: Option<u64>,
3391 pub needs_review: bool,
3392}
3393
3394#[cfg(test)]
3395mod script_status_tests {
3396 use super::*;
3397
3398 #[test]
3399 fn script_status_roundtrips_and_old_supervisor_entries_remain_readable() {
3400 let old = SupervisorEntry::new(
3401 "example",
3402 "running",
3403 true,
3404 true,
3405 SupervisorHealthStatus::Unknown,
3406 );
3407 let value = serde_json::to_value(&old).unwrap();
3408 assert!(value.get("script").is_none());
3409 assert!(serde_json::from_value::<SupervisorEntry>(value)
3410 .unwrap()
3411 .script
3412 .is_none());
3413 let current = old.with_script(Some(ScriptModuleStatus {
3414 runtime: "bun".into(),
3415 bun_version: None,
3416 path: "bundle.js".into(),
3417 sha256: Some("ab".repeat(32)),
3418 size: Some(3),
3419 needs_review: true,
3420 }));
3421 let decoded: SupervisorEntry =
3422 serde_json::from_slice(&serde_json::to_vec(¤t).unwrap()).unwrap();
3423 assert_eq!(decoded, current);
3424 }
3425}
3426
3427#[derive(Debug, Clone, PartialEq)]
3430pub enum ChildResourceUsage {
3431 Measured(ChildResourceReading),
3432 Unavailable {
3433 reason: ChildResourceUnavailableReason,
3434 },
3435 Unknown {
3438 tag: String,
3439 body: OrderedJsonObject,
3440 },
3441}
3442
3443#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3446#[non_exhaustive]
3447pub struct ChildResourceReading {
3448 pub memory_bytes: u64,
3451 pub memory_kind: ChildMemoryKind,
3452 #[serde(default, skip_serializing_if = "Option::is_none")]
3455 pub swap_bytes: Option<u64>,
3456 pub cpu_user_ms: u64,
3460 pub cpu_system_ms: u64,
3463}
3464
3465impl ChildResourceReading {
3466 #[must_use]
3468 pub fn new(
3469 memory_bytes: u64,
3470 memory_kind: ChildMemoryKind,
3471 cpu_user_ms: u64,
3472 cpu_system_ms: u64,
3473 ) -> Self {
3474 Self {
3475 memory_bytes,
3476 memory_kind,
3477 cpu_user_ms,
3478 cpu_system_ms,
3479 swap_bytes: None,
3480 }
3481 }
3482
3483 #[must_use]
3485 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3486 self.swap_bytes = swap_bytes;
3487 self
3488 }
3489}
3490
3491open_string_enum! {
3492 ChildMemoryKind {
3494 PhysFootprint => "phys_footprint",
3498 ResidentSet => "resident_set",
3501 WindowsWorkingSet => "windows_working_set",
3504 }
3505}
3506
3507open_string_enum! {
3508 ChildResourceUnavailableReason {
3510 NotRunning => "not_running",
3512 UnsupportedPlatform => "unsupported_platform",
3514 Unreadable => "unreadable",
3517 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3520 }
3521}
3522
3523#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3524#[serde(rename_all = "snake_case")]
3525pub enum SupervisorHealthStatus {
3526 Ok,
3527 Degraded,
3528 Failing,
3529 Unresponsive,
3530 Unknown,
3531}
3532
3533#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3534pub struct SupervisorHealthEntry {
3535 pub module_id: String,
3536 pub status: SupervisorHealthStatus,
3537 #[serde(default, skip_serializing_if = "Option::is_none")]
3543 pub detail: Option<String>,
3544 #[serde(default, skip_serializing_if = "Option::is_none")]
3549 pub metrics: Option<serde_json::Value>,
3550 pub consecutive_failures: u32,
3551 #[serde(default)]
3554 pub late_answer_count: u64,
3555 #[serde(default, skip_serializing_if = "Option::is_none")]
3557 pub last_late_answer_latency_ms: Option<u64>,
3558 #[serde(default)]
3563 pub last_action: Option<String>,
3564 #[serde(default)]
3567 pub last_action_ms: Option<u64>,
3568 #[serde(default, skip_serializing_if = "Option::is_none")]
3581 pub last_probe_ms: Option<u64>,
3582}
3583
3584#[cfg(test)]
3585mod tests {
3586 #[test]
3587 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3588 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3589 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3590 assert_eq!(decoded.configured_enabled, None);
3591 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3592 }
3593
3594 #[test]
3595 fn configured_enabled_values_round_trip_in_list() {
3596 for enabled in [false, true] {
3597 let entry = SupervisorEntry::new(
3598 "provider",
3599 "running",
3600 true,
3601 true,
3602 SupervisorHealthStatus::Unknown,
3603 )
3604 .with_configured_enabled(Some(enabled));
3605 let entry_json = serde_json::to_value(&entry).unwrap();
3606 assert_eq!(entry_json["configured_enabled"], enabled);
3607 assert_eq!(
3608 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3609 entry
3610 );
3611 }
3612 }
3613
3614 #[test]
3615 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3616 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3617 volume_serial_number: u64::MAX,
3618 file_id: [
3619 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3620 ],
3621 };
3622 let agreement = super::RunningImageAgreement::Match { evidence };
3623 let encoded = serde_json::to_string(&agreement).unwrap();
3624 assert!(encoded.contains("windows_spawn_file_id"));
3625 assert_eq!(
3626 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3627 agreement
3628 );
3629 }
3630
3631 #[test]
3632 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3633 assert_eq!(
3634 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3635 device: 7,
3636 inode: 11
3637 })
3638 .unwrap(),
3639 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3640 );
3641 assert_eq!(
3642 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3643 digest: "abc".to_owned()
3644 })
3645 .unwrap(),
3646 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3647 );
3648 }
3649 use super::*;
3650 use subc_protocol::{BindIdentity, RouteTarget};
3651
3652 #[test]
3653 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3654 let entry = TerminalEntry {
3655 daemon_incarnation: Some("daemon-before-restart".into()),
3656 exit_code: Some(1),
3657 exit_signal: None,
3658 at_ms: 1_700_000_000_123,
3659 disposition: TerminalDisposition::Restarting,
3660 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3661 disposition_detail: None,
3662 };
3663 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3664 assert_eq!(
3665 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3666 ["exit_kind"],
3667 "deliberate_severance"
3668 );
3669
3670 #[derive(serde::Deserialize)]
3671 struct LegacyTerminalEntry {
3672 exit_code: Option<i32>,
3673 exit_signal: Option<i32>,
3674 at_ms: u64,
3675 disposition: TerminalDisposition,
3676 }
3677
3678 let decoded: LegacyTerminalEntry =
3679 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3680 assert_eq!(decoded.exit_code, Some(1));
3681 assert_eq!(decoded.exit_signal, None);
3682 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3683 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3684
3685 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3686 let future: TerminalEntry =
3687 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3688 assert_eq!(
3689 future.exit_kind,
3690 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3691 );
3692 }
3693
3694 #[test]
3695 fn terminal_incarnation_is_optional_for_older_daemons() {
3696 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3697 "at_ms": 123,
3698 "disposition": "stopped"
3699 }))
3700 .unwrap();
3701 let encoded = serde_json::to_value(&entry).unwrap();
3702 assert_eq!(
3703 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3704 (None, None)
3705 );
3706 }
3707
3708 #[test]
3709 fn route_poll_uses_kind_field() {
3710 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3711 route_channel: 7,
3712 route_epoch: 11,
3713 kind: PollKind::Status,
3714 })
3715 .unwrap();
3716
3717 assert_eq!(body["op"], "route.poll");
3718 assert_eq!(body["route_epoch"], 11);
3719 assert_eq!(body["kind"], "status");
3720 assert!(body.get("op").is_some());
3721 }
3722
3723 #[test]
3724 fn route_open_is_internally_tagged() {
3725 let request = ClientControlRequest::RouteOpen {
3726 busy_refusals: None,
3727 target: RouteTarget::ToolProvider {
3728 module_id: "aft".to_string(),
3729 },
3730 identity: BindIdentity::new("opencode", "session-1"),
3731 consumer_identity: None,
3732 consumer_capabilities: None,
3733 role_versions: None,
3734 admission_facts: None,
3735 scope: None,
3736 };
3737
3738 let body = serde_json::to_value(request).unwrap();
3739 assert_eq!(body["op"], "route.open");
3740 assert_eq!(body["target"]["kind"], "tool_provider");
3741 assert!(body.get("consumer_identity").is_none());
3742 assert!(body.get("consumer_capabilities").is_none());
3743 assert!(body.get("role_versions").is_none());
3744 }
3745
3746 #[test]
3747 fn route_open_without_optional_fields_still_decodes() {
3748 let body = serde_json::json!({
3749 "op": "route.open",
3750 "target": { "kind": "tool_provider", "module_id": "aft" },
3751 "identity": {
3752 "project_root": "/tmp/project",
3753 "harness": "opencode",
3754 "session": "session-1"
3755 }
3756 });
3757
3758 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3759 let ClientControlRequest::RouteOpen {
3760 consumer_identity,
3761 consumer_capabilities,
3762 role_versions,
3763 admission_facts,
3764 ..
3765 } = decoded
3766 else {
3767 panic!("decoded wrong request variant");
3768 };
3769 assert_eq!(consumer_identity, None);
3770 assert_eq!(consumer_capabilities, None);
3771 assert_eq!(role_versions, None);
3772 assert_eq!(admission_facts, None);
3773 }
3774
3775 #[test]
3776 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3777 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3778 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3779 match decoded {
3780 ClientControlPush::RouteClosed {
3781 excluded_subscriptions,
3782 terminal,
3783 ..
3784 } => {
3785 assert_eq!(excluded_subscriptions, 0);
3786 assert_eq!(terminal, None);
3787 }
3788 other => panic!("unexpected push: {other:?}"),
3789 }
3790 assert!(!serde_json::to_string(&decoded)
3791 .unwrap()
3792 .contains("terminal"));
3793 }
3794
3795 #[test]
3796 fn old_route_closed_decoder_ignores_new_terminal_field() {
3797 #[derive(serde::Deserialize)]
3798 #[serde(tag = "op")]
3799 enum LegacyClientControlPush {
3800 #[serde(rename = "route.closed")]
3801 RouteClosed {
3802 module_id: String,
3803 reason: RouteCloseReason,
3804 drained: bool,
3805 abandoned: u32,
3806 },
3807 }
3808
3809 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3810 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3811 match decoded {
3812 LegacyClientControlPush::RouteClosed {
3813 module_id,
3814 reason,
3815 drained,
3816 abandoned,
3817 } => {
3818 assert_eq!(module_id, "aft-tools");
3819 assert_eq!(reason, RouteCloseReason::Crash);
3820 assert!(!drained);
3821 assert_eq!(abandoned, 0);
3822 }
3823 }
3824 }
3825
3826 #[test]
3827 fn supervisor_routes_is_a_control_plane_request() {
3828 let body = serde_json::json!({
3829 "op": "supervisor.routes",
3830 "module_id": "aft"
3831 });
3832
3833 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3834 assert_eq!(serde_json::to_value(request).unwrap(), body);
3835 }
3836
3837 #[test]
3838 fn diagnostic_string_enums_retain_unknown_wire_values() {
3839 let reason: RunningImageUnavailableReason =
3840 serde_json::from_str("\"future_reason\"").unwrap();
3841 let disposition: TerminalDisposition =
3842 serde_json::from_str("\"future_disposition\"").unwrap();
3843
3844 assert_eq!(
3845 reason,
3846 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3847 );
3848 assert_eq!(
3849 disposition,
3850 TerminalDisposition::Unknown("future_disposition".to_string())
3851 );
3852 }
3853
3854 #[test]
3855 fn diagnostic_string_enums_preserve_existing_wire_names() {
3856 let names = [
3857 (RunningImageUnavailableReason::NotRunning, "not_running"),
3858 (
3859 RunningImageUnavailableReason::UnsupportedPlatform,
3860 "unsupported_platform",
3861 ),
3862 (
3863 RunningImageUnavailableReason::RunningExecutableUnreadable,
3864 "running_executable_unreadable",
3865 ),
3866 (
3867 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3868 "running_executable_permission_denied",
3869 ),
3870 (
3871 RunningImageUnavailableReason::ProcessHidden,
3872 "process_hidden",
3873 ),
3874 (
3875 RunningImageUnavailableReason::SpawnedPathUnreadable,
3876 "spawned_path_unreadable",
3877 ),
3878 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3879 (
3880 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3881 "process_identity_unconfirmed",
3882 ),
3883 ];
3884 for (value, expected) in names {
3885 let wire = serde_json::to_string(&value).unwrap();
3886 assert_eq!(wire, format!("\"{expected}\""));
3887 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3888 assert_eq!(decoded, value);
3889 }
3890
3891 for (value, expected) in [
3892 (TerminalDisposition::Stopped, "stopped"),
3893 (TerminalDisposition::Disabled, "disabled"),
3894 (TerminalDisposition::Failed, "failed"),
3895 (TerminalDisposition::Restarting, "restarting"),
3896 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3897 ] {
3898 let wire = serde_json::to_string(&value).unwrap();
3899 assert_eq!(wire, format!("\"{expected}\""));
3900 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3901 assert_eq!(decoded, value);
3902 }
3903 }
3904
3905 #[test]
3906 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3907 let entry = SupervisorEntry::new(
3908 "waiting-module",
3909 "starting",
3910 true,
3911 false,
3912 SupervisorHealthStatus::Unknown,
3913 );
3914 let old_wire = serde_json::to_value(&entry).unwrap();
3915 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3916 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3917 assert_eq!(decoded.waiting_for_previous_pid, None);
3918 let entry = entry.with_waiting_for_previous_pid(Some(42));
3919 let wire = serde_json::to_value(&entry).unwrap();
3920 assert_eq!(wire["waiting_for_previous_pid"], 42);
3921 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3922 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3923 }
3924
3925 #[test]
3926 fn supervisor_waiting_previous_detail_is_optional_and_round_trips() {
3927 let entry = SupervisorEntry::new(
3928 "worker",
3929 "starting",
3930 true,
3931 false,
3932 SupervisorHealthStatus::Unknown,
3933 )
3934 .with_waiting_for_previous_pid(Some(41));
3935 let old_wire = serde_json::to_value(&entry).unwrap();
3936 assert!(old_wire.get("waiting_for_previous_detail").is_none());
3937 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3938 assert_eq!(decoded.waiting_for_previous_detail, None);
3939 let detail = "waiting: container survivors (pids [42])";
3940 let wire =
3941 serde_json::to_value(entry.with_waiting_for_previous_detail(Some(detail.into())))
3942 .unwrap();
3943 assert_eq!(wire["waiting_for_previous_pid"], 41);
3944 assert_eq!(wire["waiting_for_previous_detail"], detail);
3945 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3946 assert_eq!(decoded.waiting_for_previous_detail.as_deref(), Some(detail));
3947 }
3948
3949 #[test]
3950 fn diagnostic_string_enums_reject_non_string_bodies() {
3951 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3952 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3953 }
3954
3955 #[test]
3956 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3957 let body = serde_json::json!({
3958 "op": "supervisor.provenance",
3959 "daemon": {
3960 "daemon_build": {},
3961 "daemon_observed": {
3962 "running_image": {
3963 "status": "unavailable",
3964 "reason": "not_running"
3965 }
3966 }
3967 },
3968 "modules": [
3969 {
3970 "module_id": "future",
3971 "module_declared": { "status": "unverifiable" },
3972 "daemon_observed": {
3973 "running_image": {
3974 "status": "unavailable",
3975 "reason": "future_reason"
3976 }
3977 }
3978 },
3979 {
3980 "module_id": "healthy-a",
3981 "module_declared": { "status": "unverifiable" },
3982 "daemon_observed": {
3983 "running_image": {
3984 "status": "match",
3985 "evidence": {
3986 "method": "linux_proc_sha256",
3987 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3988 }
3989 }
3990 }
3991 },
3992 {
3993 "module_id": "healthy-b",
3994 "module_declared": { "status": "unverifiable" },
3995 "daemon_observed": {
3996 "running_image": {
3997 "status": "unavailable",
3998 "reason": "unsupported_platform"
3999 }
4000 }
4001 }
4002 ]
4003 });
4004
4005 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
4006 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
4007 panic!("decoded wrong response variant");
4008 };
4009 assert_eq!(modules.len(), 3);
4010 assert_eq!(modules[0].module_id, "future");
4011 assert_eq!(
4012 modules[0].daemon_observed.running_image,
4013 RunningImageAgreement::Unavailable {
4014 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
4015 }
4016 );
4017 assert_eq!(modules[1].module_id, "healthy-a");
4018 assert_eq!(modules[2].module_id, "healthy-b");
4019 }
4020
4021 #[test]
4022 fn tagged_unknown_values_retain_tag_and_body() {
4023 macro_rules! assert_unknown_round_trip {
4024 ($ty:ident, $field:literal, $value:expr) => {
4025 let value = $value;
4026 let wire = serde_json::to_string(&value).unwrap();
4027 let decoded: $ty = serde_json::from_str(&wire).unwrap();
4028 match decoded {
4029 $ty::Unknown { tag, body } => {
4030 assert_eq!(tag, value[$field].as_str().unwrap());
4031 assert_eq!(serde_json::to_value(&body).unwrap(), value);
4032 }
4033 _ => panic!("decoded known variant"),
4034 }
4035 };
4036 }
4037
4038 assert_unknown_round_trip!(
4039 ModuleDeclaredProvenance,
4040 "status",
4041 serde_json::json!({"status": "future", "build": {"version": 7}})
4042 );
4043 assert_unknown_round_trip!(
4044 RunningImageAgreement,
4045 "status",
4046 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
4047 );
4048 assert_unknown_round_trip!(
4049 RunningImageEvidence,
4050 "method",
4051 serde_json::json!({"method": "future", "digest": "abc"})
4052 );
4053 assert_unknown_round_trip!(
4054 SupervisorRouteConsumer,
4055 "kind",
4056 serde_json::json!({"kind": "future", "module_id": "m"})
4057 );
4058 assert_unknown_round_trip!(
4059 StderrCaptureState,
4060 "state",
4061 serde_json::json!({"state": "future", "reason": "because"})
4062 );
4063 assert_unknown_round_trip!(
4064 StderrTailEntry,
4065 "kind",
4066 serde_json::json!({"kind": "future", "text": "line"})
4067 );
4068 assert_unknown_round_trip!(
4069 ChildResourceUsage,
4070 "status",
4071 serde_json::json!({"status": "future", "memory_bytes": 1})
4072 );
4073 }
4074
4075 #[test]
4076 fn child_resource_usage_round_trips_both_known_states() {
4077 let measured = ChildResourceUsage::Measured(ChildResourceReading {
4078 memory_bytes: 0,
4079 memory_kind: ChildMemoryKind::ResidentSet,
4080 swap_bytes: Some(0),
4081 cpu_user_ms: 0,
4082 cpu_system_ms: 0,
4083 });
4084 let wire = serde_json::to_value(&measured).unwrap();
4085 assert_eq!(
4086 wire,
4087 serde_json::json!({
4088 "status": "measured",
4089 "memory_bytes": 0,
4090 "memory_kind": "resident_set",
4091 "swap_bytes": 0,
4092 "cpu_user_ms": 0,
4093 "cpu_system_ms": 0
4094 })
4095 );
4096 assert_eq!(
4097 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4098 measured
4099 );
4100
4101 let unavailable = ChildResourceUsage::Unavailable {
4102 reason: ChildResourceUnavailableReason::NotRunning,
4103 };
4104 let wire = serde_json::to_value(&unavailable).unwrap();
4105 assert_eq!(
4106 wire,
4107 serde_json::json!({"status": "unavailable", "reason": "not_running"})
4108 );
4109 assert_eq!(
4110 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4111 unavailable
4112 );
4113 }
4114
4115 #[test]
4116 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
4117 let stamped: StderrTailEntry = serde_json::from_str(
4121 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
4122 )
4123 .unwrap();
4124 assert_eq!(
4125 stamped,
4126 StderrTailEntry::Line {
4127 text: "boom".to_string(),
4128 truncated: true,
4129 at_ms: Some(1_789_801_440_685),
4130 }
4131 );
4132 let unstamped: StderrTailEntry =
4133 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
4134 assert_eq!(
4135 unstamped,
4136 StderrTailEntry::Line {
4137 text: "boom".to_string(),
4138 truncated: false,
4139 at_ms: None,
4140 }
4141 );
4142 assert_eq!(
4145 serde_json::to_string(&unstamped).unwrap(),
4146 r#"{"kind":"line","text":"boom"}"#
4147 );
4148 assert_eq!(
4149 serde_json::to_value(&stamped).unwrap()["at_ms"],
4150 serde_json::json!(1_789_801_440_685u64)
4151 );
4152 }
4153
4154 #[test]
4155 fn tagged_unknown_values_round_trip_the_original_json() {
4156 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
4157 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4158 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4159 }
4160
4161 #[test]
4162 fn tagged_unknown_values_round_trip_trailing_tag() {
4163 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
4164 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4165 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4166
4167 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
4168 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4169 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4170 }
4171
4172 #[test]
4173 fn tagged_unknown_values_round_trip_middle_tag() {
4174 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
4175 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4176 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4177
4178 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
4179 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4180 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4181 }
4182
4183 #[test]
4184 fn tagged_unknown_values_round_trip_deep_payload() {
4185 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
4186 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4187 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4188
4189 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
4190 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4191 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4192 }
4193
4194 #[test]
4195 fn tagged_unknown_values_reject_non_object_bodies() {
4196 for wire in ["42", r#""future""#, "[]"] {
4197 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
4198 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
4199 }
4200 }
4201
4202 #[test]
4203 fn duplicate_discriminators_reject_without_panicking() {
4204 assert_eq!(
4205 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
4206 .unwrap(),
4207 ModuleDeclaredProvenance::Unverifiable
4208 );
4209 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
4210 .unwrap()
4211 {
4212 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
4213 _ => panic!("future discriminator decoded as a known variant"),
4214 }
4215
4216 let wires = [
4217 r#"{"status":"reported","status":"unverifiable"}"#,
4218 r#"{"status":"unverifiable","status":"reported"}"#,
4219 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4220 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4221 ];
4222
4223 for wire in wires {
4224 let result =
4225 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4226 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4227 assert!(
4228 result.unwrap().is_err(),
4229 "duplicate discriminator decoded: {wire}"
4230 );
4231 }
4232
4233 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4234 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4235 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4236 assert!(
4237 result.unwrap().is_err(),
4238 "duplicate discriminator decoded: {wire}"
4239 );
4240 }
4241
4242 #[test]
4243 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4244 let known_wire =
4245 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4246 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4247 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4248
4249 for wire in [
4250 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4251 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4252 ] {
4253 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4254 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4255 }
4256
4257 for wire in [
4258 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4259 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4260 ] {
4261 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4262 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4263 }
4264
4265 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4266 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4267 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4268
4269 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4270 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4271 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4272 }
4273
4274 #[test]
4275 fn tagged_unknown_member_does_not_discard_known_siblings() {
4276 let body = serde_json::json!({
4277 "modules": [{
4278 "module_id": "target",
4279 "routes": [
4280 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4281 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4282 ]
4283 }]
4284 });
4285 let decoded: ClientControlResponse = serde_json::from_value(
4286 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4287 )
4288 .unwrap();
4289 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4290 panic!("decoded wrong response variant");
4291 };
4292 assert_eq!(modules[0].routes.len(), 2);
4293 assert_eq!(
4294 modules[0].routes[1].consumer,
4295 SupervisorRouteConsumer::Direct { connection_id: 7 }
4296 );
4297 }
4298}
4299
4300#[cfg(test)]
4301mod launch_nonce_redaction_tests {
4302 use super::*;
4303
4304 const NONCE: &str = "nonce-f00dfeed1234abcd";
4305
4306 fn identity() -> ConsumerIdentity {
4307 ConsumerIdentity {
4308 module_id: "wernicke".to_string(),
4309 launch_nonce: NONCE.to_string(),
4310 }
4311 }
4312
4313 #[test]
4314 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4315 let printed = format!("{:?}", identity());
4316 assert!(printed.contains("wernicke"), "{printed}");
4317 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4318 }
4319
4320 #[test]
4321 fn route_open_request_debug_never_prints_the_nonce() {
4322 let request = ClientControlRequest::RouteOpen {
4323 busy_refusals: None,
4324 target: subc_protocol::RouteTarget::ToolProvider {
4325 module_id: "broca".to_string(),
4326 },
4327 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4328 consumer_identity: Some(identity()),
4329 consumer_capabilities: None,
4330 role_versions: None,
4331 admission_facts: None,
4332 scope: None,
4333 };
4334 let printed = format!("{request:?}");
4335 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4336 }
4337}
4338
4339#[cfg(test)]
4340mod reader_skew_tests {
4341 use super::*;
4342 use serde_json::{json, Value};
4343
4344 fn catalog() -> Value {
4345 json!({"module_id": "provider", "roles": [], "control_ops": []})
4346 }
4347
4348 fn reply() -> Value {
4349 json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4350 }
4351
4352 fn target() -> Value {
4353 json!({
4354 "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4355 "authority_epoch": 23, "first_party": true,
4356 "approved_declarations_digest": "approved"
4357 })
4358 }
4359
4360 fn request() -> Value {
4361 json!({
4362 "op": "route.open",
4363 "target": {"kind": "tool_provider", "module_id": "provider"},
4364 "identity": {"harness": "test", "session": "session-1"}
4365 })
4366 }
4367
4368 #[test]
4369 fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4370 let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4371 let built = CatalogEntry::new("provider", vec![], vec![]);
4372 assert_eq!(old, built);
4373 assert_eq!(old.first_party, None);
4374 let old_bytes = serde_json::to_value(&old).unwrap();
4375 let additions = json!({
4376 "incarnation": "daemon", "spawn": 17, "first_party": false,
4377 "origin": "development", "requested_declarations_digest": "requested",
4378 "approved_declarations_digest": "approved"
4379 });
4380 let mut body = catalog();
4381 for (key, value) in additions.as_object().unwrap() {
4382 assert!(old_bytes.get(key).is_none(), "{key}");
4383 body[key] = value.clone();
4384 }
4385 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4386 let encoded = serde_json::to_value(&decoded).unwrap();
4387 for (key, value) in additions.as_object().unwrap() {
4388 assert_eq!(&encoded[key], value, "{key}");
4389 }
4390 assert_eq!(decoded.first_party, Some(false));
4391 assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4392 }
4393
4394 #[test]
4395 fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4396 let mut body = catalog();
4397 body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4398 body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4399 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4400 let encoded = serde_json::to_value(decoded).unwrap();
4401 for key in ["requested_declarations", "approved_declarations"] {
4402 assert_eq!(encoded[key], body[key]);
4403 }
4404 let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4405 assert_eq!(unfiltered.approved_declarations, None);
4406 assert_eq!(unfiltered.requested_declarations, None);
4407 }
4408
4409 #[test]
4410 fn reader_skew_catalog_unknown_origin_is_other() {
4411 let mut body = catalog();
4412 body["origin"] = json!("future-origin");
4413 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4414 assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4415 }
4416
4417 #[test]
4418 fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4419 let mut body = catalog();
4420 body["spawn"] = json!(9_007_199_254_740_991_u64);
4421 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4422 assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4423 for invalid in [
4424 json!(9_007_199_254_740_992_u64),
4425 json!(-1),
4426 json!(1.5),
4427 json!("17"),
4428 ] {
4429 body["spawn"] = invalid;
4430 assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4431 }
4432 }
4433
4434 #[test]
4435 fn reader_skew_catalog_watch_request_uses_subscription_op() {
4436 let body = json!({"op": "catalog.watch"});
4437 let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4438 assert_eq!(request, CatalogWatchRequest::new());
4439 assert_eq!(serde_json::to_value(request).unwrap(), body);
4440 assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4441 for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4442 assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4443 }
4444 }
4445
4446 #[test]
4447 fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4448 for generation in [0, 19, 42] {
4449 let body = json!({"op": "catalog.watch", "generation": generation});
4450 let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4451 assert_eq!(push, CatalogWatchResponse::new(generation));
4452 assert_eq!(serde_json::to_value(push).unwrap(), body);
4453 }
4454 assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4455 for invalid in [
4456 json!({"op": "catalog.watch"}),
4457 json!({"op": "activity.subscribe", "generation": 1}),
4458 ] {
4459 assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4460 }
4461 }
4462
4463 #[test]
4464 fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4465 let mut body = reply();
4466 let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4467 let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4468 assert_eq!(empty, RouteOpenReplyExt::new());
4469 empty.write_to(&mut body).unwrap();
4470 assert_eq!(body, reply());
4471 body["target"] = target();
4472 let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4473 assert_eq!(
4474 decoded.target.as_ref().unwrap().kind,
4475 RouteOpenTargetKind::Spawn
4476 );
4477 let mut encoded = reply();
4478 RouteOpenReplyExt::new()
4479 .with_target(decoded.target)
4480 .write_to(&mut encoded)
4481 .unwrap();
4482 assert_eq!(encoded, body);
4483 assert_eq!(
4484 serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4485 legacy
4486 );
4487 RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4488 assert_eq!(encoded, reply());
4489 }
4490
4491 #[test]
4492 fn reader_skew_route_open_incomplete_target_is_unmarked() {
4493 let mut body = reply();
4494 body["target"] = target();
4495 assert!(RouteOpenReplyExt::read_from(&body)
4496 .unwrap()
4497 .target
4498 .is_some());
4499 for key in [
4500 "incarnation",
4501 "kind",
4502 "spawn",
4503 "authority_epoch",
4504 "first_party",
4505 "approved_declarations_digest",
4506 ] {
4507 let mut incomplete = body.clone();
4508 incomplete["target"].as_object_mut().unwrap().remove(key);
4509 assert_eq!(
4510 RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4511 None,
4512 "{key}"
4513 );
4514 }
4515 body["target"] = Value::Null;
4516 assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4517 }
4518
4519 #[test]
4520 fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4521 for (kind, expected) in [
4522 ("prefix", RouteOpenTargetKind::Prefix),
4523 ("unsupervised", RouteOpenTargetKind::Unsupervised),
4524 ] {
4525 let mut body = reply();
4526 body["target"] = target();
4527 body["target"]["kind"] = json!(kind);
4528 body["target"]["spawn"] = json!("not-a-spawn");
4530 body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4531 body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4532 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4533 let target = ext.target.as_ref().unwrap();
4534 assert_eq!(target.kind, expected);
4535 assert_eq!(target.spawn, None);
4536 assert_eq!(target.authority_epoch, None);
4537 assert_eq!(target.approved_declarations_digest, None);
4538 assert!(!target.first_party);
4539 let mut encoded = reply();
4540 ext.write_to(&mut encoded).unwrap();
4541 for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
4542 assert!(encoded["target"].get(key).is_none());
4543 }
4544 }
4545 }
4546
4547 #[test]
4548 fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4549 let mut body = reply();
4550 body["target"] = target();
4551 body["target"]["kind"] = json!("future-kind");
4552 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4553 let target = ext.target.unwrap();
4554 assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4555 assert_eq!(target.spawn, None);
4556 assert_eq!(target.authority_epoch, None);
4557 assert_eq!(target.approved_declarations_digest, None);
4558 assert!(!target.first_party);
4559 }
4560
4561 #[test]
4562 fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4563 for field in ["spawn", "authority_epoch"] {
4564 let mut body = reply();
4565 body["target"] = target();
4566 body["target"][field] = json!(9_007_199_254_740_991_u64);
4567 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4568 assert_eq!(
4569 serde_json::to_value(ext).unwrap()["target"][field],
4570 9_007_199_254_740_991_u64
4571 );
4572 for invalid in [
4573 json!(9_007_199_254_740_992_u64),
4574 json!(-1),
4575 json!(1.5),
4576 json!("17"),
4577 ] {
4578 body["target"][field] = invalid;
4579 assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4580 let mut incomplete = body.clone();
4581 incomplete["target"]
4582 .as_object_mut()
4583 .unwrap()
4584 .remove("incarnation");
4585 assert!(
4586 RouteOpenReplyExt::read_from(&incomplete).is_err(),
4587 "{field}"
4588 );
4589 }
4590 }
4591 }
4592
4593 #[test]
4594 fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4595 let mut body = request();
4596 let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4597 assert_eq!(
4598 RouteOpenRequestExt::read_from(&body).unwrap(),
4599 RouteOpenRequestExt::new()
4600 );
4601 RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4602 assert_eq!(body, request());
4603 body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4604 let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4605 assert_eq!(
4606 decoded.accepts_close_reasons,
4607 Some(vec!["authority_changed".into(), "future-reason".into()])
4608 );
4609 let mut encoded = request();
4610 RouteOpenRequestExt::new()
4611 .with_accepts_close_reasons(decoded.accepts_close_reasons)
4612 .write_to(&mut encoded)
4613 .unwrap();
4614 assert_eq!(encoded, body);
4615 assert_eq!(
4616 serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4617 legacy
4618 );
4619 RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4620 assert_eq!(encoded, request());
4621 assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4622 }
4623
4624 #[test]
4625 fn reader_skew_route_open_helpers_refuse_other_bodies() {
4626 for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4627 assert!(RouteOpenRequestExt::read_from(&body).is_err());
4628 assert!(RouteOpenReplyExt::read_from(&body).is_err());
4629 assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4630 assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4631 }
4632 }
4633
4634 #[test]
4635 fn reader_skew_route_open_target_constructor_validates_like_reader() {
4636 let spawn = RouteOpenTarget::new(
4637 "daemon",
4638 RouteOpenTargetKind::Spawn,
4639 Some(17),
4640 Some(23),
4641 true,
4642 Some("approved".into()),
4643 )
4644 .unwrap();
4645 assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4646 for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4647 assert!(RouteOpenTarget::new(
4648 "daemon",
4649 RouteOpenTargetKind::Spawn,
4650 Some(spawn),
4651 Some(epoch),
4652 true,
4653 Some("approved".into())
4654 )
4655 .is_err());
4656 }
4657 }
4658}
4659
4660#[cfg(test)]
4661mod claim_wire_tests {
4662 use super::*;
4663 use serde_json::{json, Value};
4664
4665 fn legacy_provenance() -> SupervisorModuleProvenance {
4666 SupervisorModuleProvenance {
4667 module_id: "worker".into(),
4668 module_declared: ModuleDeclaredProvenance::Unverifiable,
4669 daemon_observed: SupervisorObservedProcess {
4670 launch_nonce_source: None,
4671 pid: None,
4672 spawned_at_ms: None,
4673 spawned_from: None,
4674 running_image: RunningImageAgreement::Unavailable {
4675 reason: RunningImageUnavailableReason::NotRunning,
4676 },
4677 },
4678 }
4679 }
4680
4681 #[test]
4682 fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4683 let legacy = legacy_provenance();
4684 let original = serde_json::to_value(&legacy).unwrap();
4685 let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4686 assert_eq!(absent.registration, None);
4687 let mut wire = original.clone();
4688 absent.write_to(&mut wire).unwrap();
4689 assert_eq!(wire, original);
4690 for (method, spelling) in [
4691 (RegistrationMethod::Channel, "channel"),
4692 (RegistrationMethod::Nonce, "nonce"),
4693 ] {
4694 let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4695 ext.write_to(&mut wire).unwrap();
4696 assert_eq!(wire["registration"], spelling);
4697 assert_eq!(
4698 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4699 ext
4700 );
4701 let old_reader: SupervisorModuleProvenance =
4702 serde_json::from_value(wire.clone()).unwrap();
4703 assert_eq!(old_reader, legacy);
4704 assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4705 }
4706 absent.write_to(&mut wire).unwrap();
4707 assert_eq!(wire, original);
4708 for mut invalid in [Value::Null, json!([]), json!("entry")] {
4709 assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4710 assert!(absent.write_to(&mut invalid).is_err());
4711 }
4712 }
4713
4714 #[test]
4715 fn provenance_waiting_previous_detail_preserves_legacy_entry() {
4716 let legacy = legacy_provenance();
4717 let mut wire = serde_json::to_value(&legacy).unwrap();
4718 let absent = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4719 assert_eq!(absent.waiting_for_previous_detail, None);
4720 let detail = "waiting: container survivors (pids [42])";
4721 let ext = absent
4722 .clone()
4723 .with_waiting_for_previous_detail(Some(detail.into()));
4724 ext.write_to(&mut wire).unwrap();
4725 assert_eq!(wire["waiting_for_previous_detail"], detail);
4726 assert_eq!(
4727 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4728 ext
4729 );
4730 assert_eq!(
4731 serde_json::from_value::<SupervisorModuleProvenance>(wire.clone()).unwrap(),
4732 legacy
4733 );
4734 absent.write_to(&mut wire).unwrap();
4735 assert!(wire.get("waiting_for_previous_detail").is_none());
4736 }
4737
4738 #[test]
4739 fn provenance_unknown_registration_is_not_channel_or_nonce() {
4740 let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4741 wire["registration"] = json!("future_method");
4742 let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4743 assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4744 assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4745 assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4746 wire["registration"] = json!(false);
4747 assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4748 }
4749
4750 #[test]
4751 fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4752 let original = serde_json::to_value(legacy_provenance()).unwrap();
4753 for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4754 let mut golden = original.clone();
4755 golden["registration_declaration"] = json!(declaration);
4756 let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4757 assert_eq!(
4758 serde_json::to_value(&extension).unwrap(),
4759 json!({
4760 "registration_declaration": declaration
4761 })
4762 );
4763 let mut written = original.clone();
4764 extension.write_to(&mut written).unwrap();
4765 assert_eq!(written, golden);
4766 assert_eq!(
4767 serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4768 legacy_provenance()
4769 );
4770 SupervisorModuleProvenanceExt::new()
4771 .write_to(&mut written)
4772 .unwrap();
4773 assert_eq!(written, original);
4774 }
4775 }
4776
4777 #[test]
4778 fn admission_refusal_is_optional_and_open() {
4779 let entry = SupervisorEntry::new(
4780 "worker",
4781 "stopped",
4782 true,
4783 false,
4784 SupervisorHealthStatus::Unknown,
4785 );
4786 let original = serde_json::to_value(&entry).unwrap();
4787 assert!(original.get("admission_refused").is_none());
4788 let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
4789 assert_eq!(read.admission_refused, None);
4790 assert_eq!(serde_json::to_value(read).unwrap(), original);
4791 assert_eq!(
4792 REGISTRATION_CHANNEL_UNSUPPORTED,
4793 "registration_channel_unsupported"
4794 );
4795 for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
4796 let mut wire = original.clone();
4797 wire["admission_refused"] = json!(reason);
4798 let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
4799 assert_eq!(read.admission_refused.as_deref(), Some(reason));
4800 assert_eq!(serde_json::to_value(read).unwrap(), wire);
4801 let built = entry.clone().with_admission_refused(Some(reason.into()));
4802 assert_eq!(serde_json::to_value(built).unwrap(), wire);
4803 }
4804 }
4805}