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