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 OperationGroup, 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 #[serde(default, skip_serializing_if = "Option::is_none")]
590 summary: Option<String>,
591 },
592 #[serde(rename = "supervisor.health")]
593 SupervisorHealth {
594 generation: u64,
595 modules: Vec<SupervisorHealthEntry>,
596 },
597 #[serde(rename = "supervisor.routes")]
598 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
599 #[serde(rename = "supervisor.provenance")]
600 SupervisorProvenance {
601 daemon: SupervisorDaemonProvenance,
602 modules: Vec<SupervisorModuleProvenance>,
603 },
604 #[serde(rename = "supervisor.stderr_tail")]
605 SupervisorStderrTail {
606 module_id: String,
607 #[serde(flatten)]
608 tail: StderrTail,
609 },
610 #[serde(rename = "supervisor.terminals")]
611 SupervisorTerminals {
612 module_id: String,
613 #[serde(flatten)]
614 terminals: TerminalHistory,
615 },
616}
617
618pub const ROUTE_CLOSE_REASONS_CAPABILITY: &str = "route-close-reasons/v1";
620
621#[non_exhaustive]
625#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
626pub struct RouteOpenRequestExt {
627 #[serde(default, skip_serializing_if = "Option::is_none")]
628 pub accepts_close_reasons: Option<Vec<String>>,
629}
630
631impl RouteOpenRequestExt {
632 pub fn new() -> Self {
633 Self::default()
634 }
635
636 #[must_use]
637 pub fn with_accepts_close_reasons(mut self, reasons: Option<Vec<String>>) -> Self {
638 self.accepts_close_reasons = reasons;
639 self
640 }
641
642 pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
644 require_route_open_object(body)?;
645 serde_json::from_value(body.clone())
646 }
647
648 pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
651 write_route_open_ext(body, self, &["accepts_close_reasons"])
652 }
653}
654
655#[non_exhaustive]
658#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
659pub struct RouteOpenReplyExt {
660 #[serde(
662 default,
663 skip_serializing_if = "Option::is_none",
664 deserialize_with = "deserialize_route_open_target"
665 )]
666 pub target: Option<RouteOpenTarget>,
667}
668
669impl RouteOpenReplyExt {
670 pub fn new() -> Self {
671 Self::default()
672 }
673
674 #[must_use]
675 pub fn with_target(mut self, target: Option<RouteOpenTarget>) -> Self {
676 self.target = target;
677 self
678 }
679
680 pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
682 require_route_open_object(body)?;
683 serde_json::from_value(body.clone())
684 }
685
686 pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
689 write_route_open_ext(body, self, &["target"])
690 }
691}
692
693fn require_route_open_object(body: &serde_json::Value) -> serde_json::Result<()> {
694 if body.is_object()
695 && body.get("op").and_then(serde_json::Value::as_str) == Some(ops::ROUTE_OPEN)
696 {
697 Ok(())
698 } else {
699 Err(serde_json::Error::custom(
700 "expected a route.open body object",
701 ))
702 }
703}
704
705fn write_route_open_ext(
706 body: &mut serde_json::Value,
707 ext: &impl Serialize,
708 keys: &[&str],
709) -> serde_json::Result<()> {
710 require_route_open_object(body)?;
711 let serde_json::Value::Object(fields) = serde_json::to_value(ext)? else {
712 unreachable!("route.open companions serialize as objects");
713 };
714 let object = body.as_object_mut().expect("validated route.open object");
715 for key in keys {
716 object.remove(*key);
717 }
718 object.extend(fields);
719 Ok(())
720}
721
722#[non_exhaustive]
724#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
725#[serde(rename_all = "snake_case")]
726pub enum RouteOpenTargetKind {
727 Spawn,
728 Prefix,
729 Unsupervised,
730 #[serde(other)]
731 Unknown,
732}
733
734#[non_exhaustive]
737#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
738pub struct RouteOpenTarget {
739 pub incarnation: String,
740 pub kind: RouteOpenTargetKind,
741 #[serde(skip_serializing_if = "Option::is_none")]
742 pub spawn: Option<u64>,
743 #[serde(skip_serializing_if = "Option::is_none")]
744 pub authority_epoch: Option<u64>,
745 pub first_party: bool,
746 #[serde(skip_serializing_if = "Option::is_none")]
747 pub approved_declarations_digest: Option<String>,
748 #[serde(skip_serializing_if = "Option::is_none")]
751 pub effective_declarations_digest: Option<String>,
752}
753
754impl RouteOpenTarget {
755 pub fn new(
758 incarnation: impl Into<String>,
759 kind: RouteOpenTargetKind,
760 spawn: Option<u64>,
761 authority_epoch: Option<u64>,
762 first_party: bool,
763 approved_declarations_digest: Option<String>,
764 ) -> serde_json::Result<Self> {
765 serde_json::from_value(serde_json::json!({
766 "incarnation": incarnation.into(), "kind": kind,
767 "spawn": spawn, "authority_epoch": authority_epoch,
768 "first_party": first_party,
769 "approved_declarations_digest": approved_declarations_digest,
770 }))
771 }
772
773 #[must_use]
775 pub fn with_effective_declarations_digest(mut self, digest: Option<String>) -> Self {
776 if self.kind == RouteOpenTargetKind::Spawn {
777 self.effective_declarations_digest = digest;
778 }
779 self
780 }
781}
782
783impl<'de> Deserialize<'de> for RouteOpenTarget {
784 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
785 decode_route_open_target(serde_json::Value::deserialize(decoder)?)
786 .map_err(D::Error::custom)?
787 .ok_or_else(|| D::Error::custom("incomplete route.open target"))
788 }
789}
790
791fn deserialize_route_open_target<'de, D: Deserializer<'de>>(
792 decoder: D,
793) -> Result<Option<RouteOpenTarget>, D::Error> {
794 decode_route_open_target(serde_json::Value::deserialize(decoder)?).map_err(D::Error::custom)
795}
796
797fn decode_route_open_target(
798 mut value: serde_json::Value,
799) -> serde_json::Result<Option<RouteOpenTarget>> {
800 if value.is_null() {
801 return Ok(None);
802 }
803 let object = value
804 .as_object_mut()
805 .ok_or_else(|| serde_json::Error::custom("expected target object"))?;
806 let is_spawn = object.get("kind").and_then(serde_json::Value::as_str) == Some("spawn");
807 if is_spawn {
808 for field in ["spawn", "authority_epoch"] {
810 if let Some(integer) = object.get(field) {
811 deserialize_optional_attestation_integer(integer)?;
812 }
813 }
814 } else {
815 for field in [
816 "spawn",
817 "authority_epoch",
818 "approved_declarations_digest",
819 "effective_declarations_digest",
820 ] {
821 object.remove(field);
822 }
823 }
824 if ["incarnation", "kind", "first_party"]
825 .iter()
826 .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null))
827 || (is_spawn
828 && ["spawn", "authority_epoch", "approved_declarations_digest"]
829 .iter()
830 .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null)))
831 {
832 return Ok(None);
833 }
834 #[derive(Deserialize)]
835 struct Wire {
836 incarnation: String,
837 kind: RouteOpenTargetKind,
838 spawn: Option<u64>,
839 authority_epoch: Option<u64>,
840 first_party: bool,
841 approved_declarations_digest: Option<String>,
842 effective_declarations_digest: Option<serde_json::Value>,
843 }
844 let wire: Wire = serde_json::from_value(value)?;
845 Ok(Some(RouteOpenTarget {
846 incarnation: wire.incarnation,
847 kind: wire.kind,
848 spawn: wire.spawn,
849 authority_epoch: wire.authority_epoch,
850 first_party: is_spawn && wire.first_party,
851 approved_declarations_digest: wire.approved_declarations_digest,
852 effective_declarations_digest: wire
853 .effective_declarations_digest
854 .as_ref()
855 .and_then(serde_json::Value::as_str)
856 .map(str::to_owned),
857 }))
858}
859
860fn deserialize_optional_attestation_integer<'de, D: Deserializer<'de>>(
861 decoder: D,
862) -> Result<Option<u64>, D::Error> {
863 let value = Option::<u64>::deserialize(decoder)?;
864 if value.is_some_and(|integer| integer > MAX_ATTESTATION_INTEGER) {
865 return Err(D::Error::custom("attestation integer exceeds 2^53-1"));
866 }
867 Ok(value)
868}
869
870#[non_exhaustive]
873#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
874#[serde(tag = "op", rename = "catalog.watch")]
875pub struct CatalogWatchRequest {}
876
877impl CatalogWatchRequest {
878 pub const OP: &'static str = ops::CATALOG_WATCH;
879
880 pub fn new() -> Self {
881 Self {}
882 }
883}
884
885#[non_exhaustive]
889#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
890#[serde(tag = "op", rename = "catalog.watch")]
891pub struct CatalogWatchResponse {
892 pub generation: u64,
893}
894
895impl CatalogWatchResponse {
896 pub const OP: &'static str = ops::CATALOG_WATCH;
897
898 pub fn new(generation: u64) -> Self {
899 Self { generation }
900 }
901}
902
903impl<'de> Deserialize<'de> for CatalogWatchRequest {
904 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
905 #[derive(Deserialize)]
906 #[serde(tag = "op")]
907 enum Wire {
908 #[serde(rename = "catalog.watch")]
909 Body {},
910 }
911 let Wire::Body {} = Wire::deserialize(decoder)?;
912 Ok(Self::new())
913 }
914}
915
916impl<'de> Deserialize<'de> for CatalogWatchResponse {
917 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
918 #[derive(Deserialize)]
919 #[serde(tag = "op")]
920 enum Wire {
921 #[serde(rename = "catalog.watch")]
922 Body { generation: u64 },
923 }
924 let Wire::Body { generation } = Wire::deserialize(decoder)?;
925 Ok(Self::new(generation))
926 }
927}
928
929#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
934#[serde(tag = "op")]
935pub enum ClientControlPush {
936 #[serde(rename = "route.closing")]
937 RouteClosing {
938 module_id: String,
939 #[serde(default)]
942 channels: Vec<u16>,
943 reason: RouteCloseReason,
944 },
945 #[serde(rename = "route.closed")]
946 RouteClosed {
947 module_id: String,
948 #[serde(default)]
951 channels: Vec<u16>,
952 reason: RouteCloseReason,
953 drained: bool,
955 abandoned: u32,
958 #[serde(default)]
960 excluded_subscriptions: u32,
961 #[serde(default, skip_serializing_if = "Option::is_none")]
967 terminal: Option<bool>,
968 },
969}
970
971#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
973pub struct SpawnCursor {
974 pub daemon_incarnation: String,
975 pub seq: u64,
976}
977
978#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
980pub struct LiveSpawn {
981 pub module_id: String,
982 pub spawn_generation: u64,
988 pub pid: u32,
989 pub spawned_at_ms: u64,
990}
991
992#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
994pub struct SpawnSnapshot {
995 pub cursor: SpawnCursor,
996 pub ring_bound: u64,
998 pub live: Vec<LiveSpawn>,
999}
1000
1001#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1003#[serde(rename_all = "snake_case")]
1004pub enum SpawnEventKind {
1005 Spawned,
1006 Exited,
1007}
1008
1009#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1015pub struct SpawnEvent {
1016 pub cursor: SpawnCursor,
1017 pub kind: SpawnEventKind,
1018 pub module_id: String,
1019 pub spawn_generation: u64,
1021 pub pid: u32,
1022 #[serde(default, skip_serializing_if = "Option::is_none")]
1023 pub exit_code: Option<i32>,
1024 #[serde(default, skip_serializing_if = "Option::is_none")]
1025 pub exit_signal: Option<i32>,
1026}
1027
1028#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1030pub struct StderrTail {
1031 pub capture: StderrCaptureState,
1032 pub entries: Vec<StderrTailEntry>,
1033 #[serde(default, skip_serializing_if = "is_zero_u64")]
1042 pub dropped_lines: u64,
1043}
1044
1045#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1047pub struct SupervisorRouteModule {
1048 pub module_id: String,
1049 pub routes: Vec<SupervisorRoute>,
1050}
1051
1052#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1054pub struct SupervisorRoute {
1055 pub consumer: SupervisorRouteConsumer,
1056 pub age_ms: u64,
1058 pub draining: bool,
1061 #[serde(default, skip_serializing_if = "Option::is_none")]
1067 pub drain_reason: Option<RouteCloseReason>,
1068 #[serde(default, skip_serializing_if = "Option::is_none")]
1070 pub opener: Option<SupervisorRouteOpener>,
1071}
1072
1073#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1075pub struct SupervisorRouteOpener {
1076 pub connection_id: u64,
1077 pub transport: SupervisorRouteTransport,
1078 #[serde(default, skip_serializing_if = "Option::is_none")]
1079 pub pid: Option<u32>,
1080 #[serde(default, skip_serializing_if = "Option::is_none")]
1081 pub command: Option<String>,
1082}
1083
1084#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1086#[serde(rename_all = "snake_case")]
1087pub enum SupervisorRouteTransport {
1088 Local,
1089 Tcp,
1090}
1091
1092#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1094pub struct SupervisorModuleProvenance {
1095 pub module_id: String,
1096 pub module_declared: ModuleDeclaredProvenance,
1097 pub daemon_observed: SupervisorObservedProcess,
1098}
1099
1100#[non_exhaustive]
1103#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1104pub struct SupervisorModuleProvenanceExt {
1105 #[serde(default, skip_serializing_if = "Option::is_none")]
1107 pub registration: Option<RegistrationMethod>,
1108 #[serde(default, skip_serializing_if = "Option::is_none")]
1112 pub registration_declaration: Option<String>,
1113 #[serde(default, skip_serializing_if = "Option::is_none")]
1115 pub waiting_for_previous_detail: Option<String>,
1116}
1117
1118impl SupervisorModuleProvenanceExt {
1119 pub fn new() -> Self {
1120 Self::default()
1121 }
1122
1123 #[must_use]
1124 pub fn with_registration(mut self, registration: Option<RegistrationMethod>) -> Self {
1125 self.registration = registration;
1126 self
1127 }
1128
1129 #[must_use]
1130 pub fn with_waiting_for_previous_detail(mut self, detail: Option<String>) -> Self {
1131 self.waiting_for_previous_detail = detail;
1132 self
1133 }
1134
1135 pub fn read_from(entry: &serde_json::Value) -> serde_json::Result<Self> {
1137 if !entry.is_object() {
1138 return Err(serde_json::Error::custom(
1139 "expected a module provenance entry object",
1140 ));
1141 }
1142 serde_json::from_value(entry.clone())
1143 }
1144
1145 pub fn write_to(&self, entry: &mut serde_json::Value) -> serde_json::Result<()> {
1148 let object = entry.as_object_mut().ok_or_else(|| {
1149 serde_json::Error::custom("expected a module provenance entry object")
1150 })?;
1151 object.remove("registration");
1152 if let Some(method) = &self.registration {
1153 object.insert("registration".into(), serde_json::to_value(method)?);
1154 }
1155 object.remove("registration_declaration");
1156 if let Some(declaration) = &self.registration_declaration {
1157 object.insert(
1158 "registration_declaration".into(),
1159 declaration.clone().into(),
1160 );
1161 }
1162 object.remove("waiting_for_previous_detail");
1163 if let Some(detail) = &self.waiting_for_previous_detail {
1164 object.insert("waiting_for_previous_detail".into(), detail.clone().into());
1165 }
1166 Ok(())
1167 }
1168}
1169
1170#[non_exhaustive]
1173#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1174#[serde(rename_all = "snake_case")]
1175pub enum RegistrationMethod {
1176 Channel,
1177 Nonce,
1178 #[serde(other)]
1179 Unknown,
1180}
1181
1182pub const REGISTRATION_CHANNEL_UNSUPPORTED: &str = "registration_channel_unsupported";
1185
1186#[derive(Debug, Clone, PartialEq)]
1188pub enum ModuleDeclaredProvenance {
1189 Reported {
1190 build: ManifestProvenance,
1191 },
1192 Unverifiable,
1193 Unknown {
1196 tag: String,
1197 body: OrderedJsonObject,
1198 },
1199}
1200
1201#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1206pub struct SupervisorObservedProcess {
1207 #[serde(default, skip_serializing_if = "Option::is_none")]
1213 pub launch_nonce_source: Option<String>,
1214 #[serde(default, skip_serializing_if = "Option::is_none")]
1215 pub pid: Option<u32>,
1216 #[serde(default, skip_serializing_if = "Option::is_none")]
1217 pub spawned_at_ms: Option<u64>,
1218 #[serde(default, skip_serializing_if = "Option::is_none")]
1219 pub spawned_from: Option<PathBuf>,
1220 pub running_image: RunningImageAgreement,
1221}
1222
1223#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1240#[non_exhaustive]
1241pub struct PendingReloadVerdict {
1242 pub path: ReloadPathAgreement,
1243 pub image: RunningImageAgreement,
1244 #[serde(default, skip_serializing_if = "Option::is_none")]
1245 pub spec: Option<LaunchSpecAgreement>,
1246}
1247
1248impl PendingReloadVerdict {
1249 #[must_use]
1251 pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
1252 Self {
1253 path,
1254 image,
1255 spec: None,
1256 }
1257 }
1258
1259 #[must_use]
1261 pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
1262 self.spec = spec;
1263 self
1264 }
1265}
1266
1267#[cfg(test)]
1268mod launch_spec_wire_tests {
1269 use super::*;
1270
1271 #[test]
1272 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
1273 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
1274 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
1275 assert_eq!(parsed.spec, None);
1276 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
1277 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
1278 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
1279 assert!(
1280 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
1281 );
1282 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
1283 let unavailable = LaunchSpecAgreement::Unavailable {
1284 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
1285 };
1286 let encoded = serde_json::to_string(&unavailable).unwrap();
1287 assert_eq!(
1288 encoded,
1289 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
1290 );
1291 assert_eq!(
1292 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
1293 unavailable
1294 );
1295 }
1296}
1297
1298#[derive(Debug, Clone, PartialEq)]
1301pub enum LaunchSpecAgreement {
1302 Match,
1303 Mismatch,
1304 Unavailable {
1305 reason: LaunchSpecUnavailableReason,
1306 },
1307 Unknown {
1308 tag: String,
1309 body: OrderedJsonObject,
1310 },
1311}
1312
1313open_string_enum! {
1314 LaunchSpecUnavailableReason {
1315 NotRunning => "not_running",
1316 SpawnedSpecUnavailable => "spawned_spec_unavailable",
1317 }
1318}
1319
1320#[derive(Debug, Clone, PartialEq)]
1322pub enum ReloadPathAgreement {
1323 Match,
1324 Mismatch {
1325 configured: PathBuf,
1326 spawned_from: PathBuf,
1327 },
1328 Unavailable {
1329 reason: ReloadPathUnavailableReason,
1330 },
1331 Unknown {
1332 tag: String,
1333 body: OrderedJsonObject,
1334 },
1335}
1336
1337open_string_enum! {
1338 ReloadPathUnavailableReason {
1340 NotRunning => "not_running",
1341 SpawnedPathUnavailable => "spawned_path_unavailable",
1342 }
1343}
1344
1345#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1347pub struct SupervisorDaemonProvenance {
1348 pub daemon_build: DaemonBuildProvenance,
1349 pub daemon_observed: DaemonObservedProcess,
1350}
1351
1352#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1354pub struct DaemonBuildProvenance {
1355 #[serde(default, skip_serializing_if = "Option::is_none")]
1356 pub build_git_sha: Option<String>,
1357 #[serde(default, skip_serializing_if = "Option::is_none")]
1358 pub build_lock_digest: Option<String>,
1359}
1360
1361#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1363pub struct DaemonObservedProcess {
1364 #[serde(default, skip_serializing_if = "Option::is_none")]
1365 pub pid: Option<u32>,
1366 #[serde(default, skip_serializing_if = "Option::is_none")]
1371 pub started_at_ms: Option<u64>,
1372 pub running_image: RunningImageAgreement,
1373}
1374
1375#[derive(Debug, Clone, PartialEq)]
1377pub enum RunningImageAgreement {
1378 Match {
1379 evidence: RunningImageEvidence,
1380 },
1381 Mismatch {
1382 running: RunningImageEvidence,
1383 disk: RunningImageEvidence,
1384 },
1385 Unavailable {
1386 reason: RunningImageUnavailableReason,
1387 },
1388 Unknown {
1391 tag: String,
1392 body: OrderedJsonObject,
1393 },
1394}
1395
1396#[derive(Debug, Clone, PartialEq)]
1398pub enum RunningImageEvidence {
1399 LinuxProcSha256 {
1400 digest: String,
1401 },
1402 MacosSpawnInode {
1403 device: u64,
1404 inode: u64,
1405 },
1406 WindowsSpawnFileId {
1408 volume_serial_number: u64,
1409 file_id: [u8; 16],
1410 },
1411 Unknown {
1414 tag: String,
1415 body: OrderedJsonObject,
1416 },
1417}
1418
1419open_string_enum! {
1420 RunningImageUnavailableReason {
1422 NotRunning => "not_running",
1423 NotYetMeasured => "not_yet_measured",
1424 UnsupportedPlatform => "unsupported_platform",
1425 RunningExecutableUnreadable => "running_executable_unreadable",
1426 RunningExecutablePermissionDenied => "running_executable_permission_denied",
1427 ProcessHidden => "process_hidden",
1428 SpawnedPathUnreadable => "spawned_path_unreadable",
1429 HashFailed => "hash_failed",
1430 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
1431 }
1432}
1433
1434#[derive(Debug, Clone, PartialEq)]
1440pub enum SupervisorRouteConsumer {
1441 Reserved {
1442 module_id: String,
1443 },
1444 Direct {
1445 connection_id: u64,
1446 },
1447 Unknown {
1450 tag: String,
1451 body: OrderedJsonObject,
1452 },
1453}
1454
1455#[derive(Debug, Clone, PartialEq)]
1462pub enum StderrCaptureState {
1463 Captured,
1466 Incomplete { reason: String },
1468 NotCaptured { reason: String },
1470 Unknown {
1473 tag: String,
1474 body: OrderedJsonObject,
1475 },
1476}
1477
1478#[derive(Debug, Clone, PartialEq)]
1479pub enum StderrTailEntry {
1480 Line {
1481 text: String,
1482 truncated: bool,
1487 at_ms: Option<u64>,
1491 },
1492 ProcessStart,
1497 Unknown {
1500 tag: String,
1501 body: OrderedJsonObject,
1502 },
1503}
1504
1505#[derive(Debug, Serialize, Deserialize)]
1506#[serde(tag = "status", rename_all = "snake_case")]
1507enum ModuleDeclaredProvenanceWire {
1508 Reported { build: ManifestProvenance },
1509 Unverifiable,
1510}
1511
1512#[derive(Debug, Serialize, Deserialize)]
1513#[serde(tag = "status", rename_all = "snake_case")]
1514enum RunningImageAgreementWire {
1515 Match {
1516 evidence: RunningImageEvidence,
1517 },
1518 Mismatch {
1519 running: RunningImageEvidence,
1520 disk: RunningImageEvidence,
1521 },
1522 Unavailable {
1523 reason: RunningImageUnavailableReason,
1524 },
1525}
1526
1527#[derive(Debug, Serialize, Deserialize)]
1528#[serde(tag = "status", rename_all = "snake_case")]
1529enum ReloadPathAgreementWire {
1530 Match,
1531 Mismatch {
1532 configured: PathBuf,
1533 spawned_from: PathBuf,
1534 },
1535 Unavailable {
1536 reason: ReloadPathUnavailableReason,
1537 },
1538}
1539
1540#[derive(Debug, Serialize, Deserialize)]
1541#[serde(tag = "status", rename_all = "snake_case")]
1542enum LaunchSpecAgreementWire {
1543 Match,
1544 Mismatch,
1545 Unavailable { reason: LaunchSpecUnavailableReason },
1546}
1547
1548#[derive(Debug, Serialize, Deserialize)]
1549#[serde(tag = "method", rename_all = "snake_case")]
1550enum RunningImageEvidenceWire {
1551 LinuxProcSha256 {
1552 digest: String,
1553 },
1554 MacosSpawnInode {
1555 device: u64,
1556 inode: u64,
1557 },
1558 WindowsSpawnFileId {
1559 volume_serial_number: u64,
1560 file_id: [u8; 16],
1561 },
1562}
1563
1564#[derive(Debug, Serialize, Deserialize)]
1565#[serde(tag = "kind", rename_all = "snake_case")]
1566enum SupervisorRouteConsumerWire {
1567 Reserved { module_id: String },
1568 Direct { connection_id: u64 },
1569}
1570
1571#[derive(Debug, Serialize, Deserialize)]
1572#[serde(tag = "state", rename_all = "snake_case")]
1573enum StderrCaptureStateWire {
1574 Captured,
1575 Incomplete { reason: String },
1576 NotCaptured { reason: String },
1577}
1578
1579#[derive(Debug, Serialize, Deserialize)]
1580#[serde(tag = "status", rename_all = "snake_case")]
1581enum ChildResourceUsageWire {
1582 Measured(ChildResourceReading),
1583 Unavailable {
1584 reason: ChildResourceUnavailableReason,
1585 },
1586}
1587
1588#[derive(Debug, Serialize, Deserialize)]
1589#[serde(tag = "kind", rename_all = "snake_case")]
1590enum StderrTailEntryWire {
1591 Line {
1592 text: String,
1593 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1594 truncated: bool,
1595 #[serde(default, skip_serializing_if = "Option::is_none")]
1598 at_ms: Option<u64>,
1599 },
1600 ProcessStart,
1601}
1602
1603#[derive(Debug, Clone, PartialEq)]
1605pub enum OrderedJsonValue {
1606 Null,
1607 Bool(bool),
1608 Number(serde_json::Number),
1609 String(String),
1610 Array(Vec<Self>),
1611 Object(OrderedJsonObject),
1612}
1613
1614#[derive(Debug, Clone, PartialEq)]
1616pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1617
1618impl OrderedJsonObject {
1619 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1621 &self.0
1622 }
1623
1624 fn into_value(self) -> serde_json::Value {
1625 serde_json::Value::Object(
1626 self.0
1627 .into_iter()
1628 .map(|(key, value)| (key, value.into_value()))
1629 .collect(),
1630 )
1631 }
1632}
1633
1634impl OrderedJsonValue {
1635 fn into_value(self) -> serde_json::Value {
1636 match self {
1637 Self::Null => serde_json::Value::Null,
1638 Self::Bool(value) => serde_json::Value::Bool(value),
1639 Self::Number(value) => serde_json::Value::Number(value),
1640 Self::String(value) => serde_json::Value::String(value),
1641 Self::Array(values) => {
1642 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1643 }
1644 Self::Object(value) => value.into_value(),
1645 }
1646 }
1647}
1648
1649impl Serialize for OrderedJsonValue {
1650 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1651 where
1652 S: Serializer,
1653 {
1654 match self {
1655 Self::Null => serializer.serialize_unit(),
1656 Self::Bool(value) => serializer.serialize_bool(*value),
1657 Self::Number(value) => value.serialize(serializer),
1658 Self::String(value) => serializer.serialize_str(value),
1659 Self::Array(values) => values.serialize(serializer),
1660 Self::Object(value) => value.serialize(serializer),
1661 }
1662 }
1663}
1664
1665impl<'de> Deserialize<'de> for OrderedJsonValue {
1666 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1667 where
1668 D: Deserializer<'de>,
1669 {
1670 struct OrderedValueVisitor;
1671
1672 impl<'de> Visitor<'de> for OrderedValueVisitor {
1673 type Value = OrderedJsonValue;
1674
1675 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1676 formatter.write_str("a JSON value with ordered object members")
1677 }
1678
1679 fn visit_unit<E>(self) -> Result<Self::Value, E>
1680 where
1681 E: serde::de::Error,
1682 {
1683 Ok(OrderedJsonValue::Null)
1684 }
1685
1686 fn visit_none<E>(self) -> Result<Self::Value, E>
1687 where
1688 E: serde::de::Error,
1689 {
1690 Ok(OrderedJsonValue::Null)
1691 }
1692
1693 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1694 where
1695 D: Deserializer<'de>,
1696 {
1697 OrderedJsonValue::deserialize(deserializer)
1698 }
1699
1700 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1701 where
1702 E: serde::de::Error,
1703 {
1704 Ok(OrderedJsonValue::Bool(value))
1705 }
1706
1707 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1708 where
1709 E: serde::de::Error,
1710 {
1711 Ok(OrderedJsonValue::Number(value.into()))
1712 }
1713
1714 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1715 where
1716 E: serde::de::Error,
1717 {
1718 Ok(OrderedJsonValue::Number(value.into()))
1719 }
1720
1721 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1722 where
1723 E: serde::de::Error,
1724 {
1725 serde_json::Number::from_f64(value)
1726 .map(OrderedJsonValue::Number)
1727 .ok_or_else(|| E::custom("non-finite JSON number"))
1728 }
1729
1730 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1731 where
1732 E: serde::de::Error,
1733 {
1734 Ok(OrderedJsonValue::String(value.to_owned()))
1735 }
1736
1737 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1738 where
1739 E: serde::de::Error,
1740 {
1741 Ok(OrderedJsonValue::String(value))
1742 }
1743
1744 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1745 where
1746 A: SeqAccess<'de>,
1747 {
1748 let mut values = Vec::new();
1749 while let Some(value) = sequence.next_element()? {
1750 values.push(value);
1751 }
1752 Ok(OrderedJsonValue::Array(values))
1753 }
1754
1755 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1756 where
1757 A: MapAccess<'de>,
1758 {
1759 let mut entries = Vec::new();
1760 while let Some((key, value)) = map.next_entry()? {
1761 entries.push((key, value));
1762 }
1763 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1764 }
1765 }
1766
1767 deserializer.deserialize_any(OrderedValueVisitor)
1768 }
1769}
1770
1771impl Serialize for OrderedJsonObject {
1772 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1773 where
1774 S: Serializer,
1775 {
1776 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1777 for (key, value) in &self.0 {
1778 map.serialize_entry(key, value)?;
1779 }
1780 map.end()
1781 }
1782}
1783
1784impl<'de> Deserialize<'de> for OrderedJsonObject {
1785 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1786 where
1787 D: Deserializer<'de>,
1788 {
1789 struct OrderedObjectVisitor;
1790
1791 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1792 type Value = OrderedJsonObject;
1793
1794 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1795 formatter.write_str("an object with ordered JSON members")
1796 }
1797
1798 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1799 where
1800 A: MapAccess<'de>,
1801 {
1802 let mut entries = Vec::new();
1803 while let Some((key, value)) = map.next_entry()? {
1804 entries.push((key, value));
1805 }
1806 Ok(OrderedJsonObject(entries))
1807 }
1808 }
1809
1810 deserializer.deserialize_map(OrderedObjectVisitor)
1811 }
1812}
1813
1814fn read_tagged<'de, D>(
1815 deserializer: D,
1816 field: &'static str,
1817) -> Result<(String, OrderedJsonObject), D::Error>
1818where
1819 D: Deserializer<'de>,
1820{
1821 let body = OrderedJsonObject::deserialize(deserializer)?;
1822 let mut tag = None;
1823 for (key, value) in body.as_entries() {
1824 if key != field {
1825 continue;
1826 }
1827 if tag.is_some() {
1828 return Err(D::Error::custom(format!(
1829 "tagged object has duplicate `{field}` field"
1830 )));
1831 }
1832 let OrderedJsonValue::String(value) = value else {
1833 return Err(D::Error::custom(format!(
1834 "tagged object has no string `{field}` field"
1835 )));
1836 };
1837 tag = Some(value);
1838 }
1839 let Some(tag) = tag else {
1840 return Err(D::Error::custom(format!(
1841 "tagged object has no string `{field}` field"
1842 )));
1843 };
1844 Ok((tag.to_string(), body))
1845}
1846
1847fn read_ordered_tagged(
1848 value: OrderedJsonValue,
1849 field: &'static str,
1850) -> Result<(String, OrderedJsonObject), String> {
1851 let OrderedJsonValue::Object(body) = value else {
1852 return Err(format!("expected tagged object with `{field}` field"));
1853 };
1854 let mut tag = None;
1855 for (key, value) in body.as_entries() {
1856 if key != field {
1857 continue;
1858 }
1859 if tag.is_some() {
1860 return Err(format!("tagged object has duplicate `{field}` field"));
1861 }
1862 let OrderedJsonValue::String(value) = value else {
1863 return Err(format!("tagged object has no string `{field}` field"));
1864 };
1865 tag = Some(value);
1866 }
1867 let Some(tag) = tag else {
1868 return Err(format!("tagged object has no string `{field}` field"));
1869 };
1870 Ok((tag.to_string(), body))
1871}
1872
1873fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1874 body.as_entries()
1875 .iter()
1876 .find_map(|(key, value)| (key == field).then_some(value))
1877}
1878
1879fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1880 match ordered_field(body, field) {
1881 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1882 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1883 None => Err(format!("tagged object has no `{field}` field")),
1884 }
1885}
1886
1887fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1888 let (tag, body) = read_ordered_tagged(value, "method")?;
1889 match tag.as_str() {
1890 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1891 digest: ordered_string(&body, "digest")?,
1892 }),
1893 "macos_spawn_inode" => {
1894 let device = ordered_field(&body, "device")
1895 .and_then(|value| match value {
1896 OrderedJsonValue::Number(number) => number.as_u64(),
1897 _ => None,
1898 })
1899 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1900 let inode = ordered_field(&body, "inode")
1901 .and_then(|value| match value {
1902 OrderedJsonValue::Number(number) => number.as_u64(),
1903 _ => None,
1904 })
1905 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1906 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1907 }
1908 "windows_spawn_file_id" => {
1909 let wire: RunningImageEvidenceWire = serde_json::from_value(
1910 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1911 )
1912 .map_err(|error| error.to_string())?;
1913 match wire {
1914 RunningImageEvidenceWire::WindowsSpawnFileId {
1915 volume_serial_number,
1916 file_id,
1917 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1918 volume_serial_number,
1919 file_id,
1920 }),
1921 _ => unreachable!(),
1922 }
1923 }
1924 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1925 }
1926}
1927
1928impl Serialize for ModuleDeclaredProvenance {
1929 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1930 where
1931 S: Serializer,
1932 {
1933 match self {
1934 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1935 build: build.clone(),
1936 }
1937 .serialize(serializer),
1938 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1939 Self::Unknown { body, .. } => body.serialize(serializer),
1940 }
1941 }
1942}
1943
1944impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1945 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1946 where
1947 D: serde::Deserializer<'de>,
1948 {
1949 let (tag, value) = read_tagged(deserializer, "status")?;
1950 match tag.as_str() {
1951 "reported" => match serde_json::from_value(value.into_value())
1952 .map_err(D::Error::custom)?
1953 {
1954 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1955 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1956 },
1957 "unverifiable" => {
1958 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1959 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1960 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1961 }
1962 }
1963 _ => Ok(Self::Unknown { tag, body: value }),
1964 }
1965 }
1966}
1967
1968impl Serialize for RunningImageAgreement {
1969 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1970 where
1971 S: Serializer,
1972 {
1973 match self {
1974 Self::Match { evidence } => RunningImageAgreementWire::Match {
1975 evidence: evidence.clone(),
1976 }
1977 .serialize(serializer),
1978 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1979 running: running.clone(),
1980 disk: disk.clone(),
1981 }
1982 .serialize(serializer),
1983 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1984 reason: reason.clone(),
1985 }
1986 .serialize(serializer),
1987 Self::Unknown { body, .. } => body.serialize(serializer),
1988 }
1989 }
1990}
1991
1992impl Serialize for ReloadPathAgreement {
1993 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1994 where
1995 S: Serializer,
1996 {
1997 match self {
1998 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1999 Self::Mismatch {
2000 configured,
2001 spawned_from,
2002 } => ReloadPathAgreementWire::Mismatch {
2003 configured: configured.clone(),
2004 spawned_from: spawned_from.clone(),
2005 }
2006 .serialize(serializer),
2007 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
2008 reason: reason.clone(),
2009 }
2010 .serialize(serializer),
2011 Self::Unknown { body, .. } => body.serialize(serializer),
2012 }
2013 }
2014}
2015
2016impl Serialize for LaunchSpecAgreement {
2017 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2018 where
2019 S: Serializer,
2020 {
2021 match self {
2022 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
2023 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
2024 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
2025 reason: reason.clone(),
2026 }
2027 .serialize(serializer),
2028 Self::Unknown { body, .. } => body.serialize(serializer),
2029 }
2030 }
2031}
2032
2033impl<'de> Deserialize<'de> for LaunchSpecAgreement {
2034 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2035 where
2036 D: Deserializer<'de>,
2037 {
2038 let (tag, body) = read_tagged(deserializer, "status")?;
2039 match tag.as_str() {
2040 "match" => Ok(Self::Match),
2041 "mismatch" => Ok(Self::Mismatch),
2042 "unavailable" => match serde_json::from_value(body.into_value())
2043 .map_err(D::Error::custom)?
2044 {
2045 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
2046 _ => unreachable!(),
2047 },
2048 _ => Ok(Self::Unknown { tag, body }),
2049 }
2050 }
2051}
2052
2053impl<'de> Deserialize<'de> for ReloadPathAgreement {
2054 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2055 where
2056 D: Deserializer<'de>,
2057 {
2058 let (tag, body) = read_tagged(deserializer, "status")?;
2059 match tag.as_str() {
2060 "match" => Ok(Self::Match),
2061 "mismatch" => {
2062 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2063 ReloadPathAgreementWire::Mismatch {
2064 configured,
2065 spawned_from,
2066 } => Ok(Self::Mismatch {
2067 configured,
2068 spawned_from,
2069 }),
2070 _ => unreachable!(),
2071 }
2072 }
2073 "unavailable" => match serde_json::from_value(body.into_value())
2074 .map_err(D::Error::custom)?
2075 {
2076 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
2077 _ => unreachable!(),
2078 },
2079 _ => Ok(Self::Unknown { tag, body }),
2080 }
2081 }
2082}
2083
2084impl<'de> Deserialize<'de> for RunningImageAgreement {
2085 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2086 where
2087 D: serde::Deserializer<'de>,
2088 {
2089 let (tag, value) = read_tagged(deserializer, "status")?;
2090 match tag.as_str() {
2091 "match" => Ok(Self::Match {
2092 evidence: decode_running_image_evidence(
2093 ordered_field(&value, "evidence")
2094 .cloned()
2095 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
2096 )
2097 .map_err(D::Error::custom)?,
2098 }),
2099 "mismatch" => Ok(Self::Mismatch {
2100 running: decode_running_image_evidence(
2101 ordered_field(&value, "running")
2102 .cloned()
2103 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
2104 )
2105 .map_err(D::Error::custom)?,
2106 disk: decode_running_image_evidence(
2107 ordered_field(&value, "disk")
2108 .cloned()
2109 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
2110 )
2111 .map_err(D::Error::custom)?,
2112 }),
2113 "unavailable" => Ok(Self::Unavailable {
2114 reason: serde_json::from_value(
2115 ordered_field(&value, "reason")
2116 .cloned()
2117 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
2118 .into_value(),
2119 )
2120 .map_err(D::Error::custom)?,
2121 }),
2122 _ => Ok(Self::Unknown { tag, body: value }),
2123 }
2124 }
2125}
2126
2127impl Serialize for ChildResourceUsage {
2128 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2129 where
2130 S: Serializer,
2131 {
2132 match self {
2133 Self::Measured(reading) => {
2134 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
2135 }
2136 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
2137 reason: reason.clone(),
2138 }
2139 .serialize(serializer),
2140 Self::Unknown { body, .. } => body.serialize(serializer),
2141 }
2142 }
2143}
2144
2145impl<'de> Deserialize<'de> for ChildResourceUsage {
2146 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2147 where
2148 D: Deserializer<'de>,
2149 {
2150 let (tag, body) = read_tagged(deserializer, "status")?;
2151 match tag.as_str() {
2152 "measured" | "unavailable" => {
2153 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2154 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
2155 ChildResourceUsageWire::Unavailable { reason } => {
2156 Ok(Self::Unavailable { reason })
2157 }
2158 }
2159 }
2160 _ => Ok(Self::Unknown { tag, body }),
2161 }
2162 }
2163}
2164
2165impl Serialize for RunningImageEvidence {
2166 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2167 where
2168 S: Serializer,
2169 {
2170 match self {
2171 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
2172 digest: digest.clone(),
2173 }
2174 .serialize(serializer),
2175 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
2176 device: *device,
2177 inode: *inode,
2178 }
2179 .serialize(serializer),
2180 Self::WindowsSpawnFileId {
2181 volume_serial_number,
2182 file_id,
2183 } => RunningImageEvidenceWire::WindowsSpawnFileId {
2184 volume_serial_number: *volume_serial_number,
2185 file_id: *file_id,
2186 }
2187 .serialize(serializer),
2188 Self::Unknown { body, .. } => body.serialize(serializer),
2189 }
2190 }
2191}
2192
2193impl<'de> Deserialize<'de> for RunningImageEvidence {
2194 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2195 where
2196 D: serde::Deserializer<'de>,
2197 {
2198 let (tag, value) = read_tagged(deserializer, "method")?;
2199 match tag.as_str() {
2200 "linux_proc_sha256" => {
2201 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2202 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
2203 Ok(Self::LinuxProcSha256 { digest })
2204 }
2205 _ => unreachable!(),
2206 }
2207 }
2208 "macos_spawn_inode" => {
2209 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2210 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
2211 Ok(Self::MacosSpawnInode { device, inode })
2212 }
2213 _ => unreachable!(),
2214 }
2215 }
2216 "windows_spawn_file_id" => {
2217 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2218 RunningImageEvidenceWire::WindowsSpawnFileId {
2219 volume_serial_number,
2220 file_id,
2221 } => Ok(Self::WindowsSpawnFileId {
2222 volume_serial_number,
2223 file_id,
2224 }),
2225 _ => unreachable!(),
2226 }
2227 }
2228 _ => Ok(Self::Unknown { tag, body: value }),
2229 }
2230 }
2231}
2232
2233impl Serialize for SupervisorRouteConsumer {
2234 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2235 where
2236 S: Serializer,
2237 {
2238 match self {
2239 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
2240 module_id: module_id.clone(),
2241 }
2242 .serialize(serializer),
2243 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
2244 connection_id: *connection_id,
2245 }
2246 .serialize(serializer),
2247 Self::Unknown { body, .. } => body.serialize(serializer),
2248 }
2249 }
2250}
2251
2252impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
2253 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2254 where
2255 D: serde::Deserializer<'de>,
2256 {
2257 let (tag, value) = read_tagged(deserializer, "kind")?;
2258 match tag.as_str() {
2259 "reserved" => {
2260 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2261 SupervisorRouteConsumerWire::Reserved { module_id } => {
2262 Ok(Self::Reserved { module_id })
2263 }
2264 _ => unreachable!(),
2265 }
2266 }
2267 "direct" => {
2268 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2269 SupervisorRouteConsumerWire::Direct { connection_id } => {
2270 Ok(Self::Direct { connection_id })
2271 }
2272 _ => unreachable!(),
2273 }
2274 }
2275 _ => Ok(Self::Unknown { tag, body: value }),
2276 }
2277 }
2278}
2279
2280impl Serialize for StderrCaptureState {
2281 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2282 where
2283 S: Serializer,
2284 {
2285 match self {
2286 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
2287 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
2288 reason: reason.clone(),
2289 }
2290 .serialize(serializer),
2291 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
2292 reason: reason.clone(),
2293 }
2294 .serialize(serializer),
2295 Self::Unknown { body, .. } => body.serialize(serializer),
2296 }
2297 }
2298}
2299
2300impl<'de> Deserialize<'de> for StderrCaptureState {
2301 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2302 where
2303 D: serde::Deserializer<'de>,
2304 {
2305 let (tag, value) = read_tagged(deserializer, "state")?;
2306 match tag.as_str() {
2307 "captured" => {
2308 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2309 StderrCaptureStateWire::Captured => Ok(Self::Captured),
2310 _ => unreachable!(),
2311 }
2312 }
2313 "incomplete" => match serde_json::from_value(value.into_value())
2314 .map_err(D::Error::custom)?
2315 {
2316 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
2317 _ => unreachable!(),
2318 },
2319 "not_captured" => match serde_json::from_value(value.into_value())
2320 .map_err(D::Error::custom)?
2321 {
2322 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
2323 _ => unreachable!(),
2324 },
2325 _ => Ok(Self::Unknown { tag, body: value }),
2326 }
2327 }
2328}
2329
2330impl Serialize for StderrTailEntry {
2331 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2332 where
2333 S: Serializer,
2334 {
2335 match self {
2336 Self::Line {
2337 text,
2338 truncated,
2339 at_ms,
2340 } => StderrTailEntryWire::Line {
2341 text: text.clone(),
2342 truncated: *truncated,
2343 at_ms: *at_ms,
2344 }
2345 .serialize(serializer),
2346 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
2347 Self::Unknown { body, .. } => body.serialize(serializer),
2348 }
2349 }
2350}
2351
2352impl<'de> Deserialize<'de> for StderrTailEntry {
2353 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2354 where
2355 D: serde::Deserializer<'de>,
2356 {
2357 let (tag, value) = read_tagged(deserializer, "kind")?;
2358 match tag.as_str() {
2359 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2360 StderrTailEntryWire::Line {
2361 text,
2362 truncated,
2363 at_ms,
2364 } => Ok(Self::Line {
2365 text,
2366 truncated,
2367 at_ms,
2368 }),
2369 _ => unreachable!(),
2370 },
2371 "process_start" => {
2372 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2373 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
2374 _ => unreachable!(),
2375 }
2376 }
2377 _ => Ok(Self::Unknown { tag, body: value }),
2378 }
2379 }
2380}
2381
2382fn is_zero_u64(value: &u64) -> bool {
2383 *value == 0
2384}
2385
2386fn default_true() -> bool {
2387 true
2388}
2389
2390#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2392pub struct TerminalHistory {
2393 pub daemon_started_at_ms: u64,
2395 pub entries: Vec<TerminalEntry>,
2396 #[serde(default, skip_serializing_if = "is_zero_u64")]
2399 pub dropped: u64,
2400 #[serde(default, skip_serializing_if = "is_zero_u64")]
2403 pub journal_skipped_lines: u64,
2404 #[serde(default, skip_serializing_if = "is_zero_u64")]
2406 pub journal_read_errors: u64,
2407 #[serde(default, skip_serializing_if = "is_zero_u64")]
2409 pub journal_write_failures: u64,
2410}
2411
2412#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2414pub struct TerminalEntry {
2415 #[serde(default, skip_serializing_if = "Option::is_none")]
2418 pub daemon_incarnation: Option<String>,
2419 #[serde(default, skip_serializing_if = "Option::is_none")]
2420 pub exit_code: Option<i32>,
2421 #[serde(default, skip_serializing_if = "Option::is_none")]
2422 pub exit_signal: Option<i32>,
2423 pub at_ms: u64,
2424 pub disposition: TerminalDisposition,
2425 #[serde(default, skip_serializing_if = "Option::is_none")]
2429 pub exit_kind: Option<TerminalExitKind>,
2430 #[serde(default, skip_serializing_if = "Option::is_none")]
2437 pub disposition_detail: Option<String>,
2438}
2439
2440#[derive(Debug, Clone, PartialEq, Eq)]
2445pub enum TerminalExitKind {
2446 Clean,
2447 Crash,
2448 DeliberateSeverance,
2449 Unknown(String),
2450}
2451
2452impl TerminalExitKind {
2453 fn wire_name(&self) -> &str {
2454 match self {
2455 Self::Clean => "clean",
2456 Self::Crash => "crash",
2457 Self::DeliberateSeverance => "deliberate_severance",
2458 Self::Unknown(value) => value,
2459 }
2460 }
2461}
2462
2463impl Serialize for TerminalExitKind {
2464 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2465 where
2466 S: serde::Serializer,
2467 {
2468 serializer.serialize_str(self.wire_name())
2469 }
2470}
2471
2472impl<'de> Deserialize<'de> for TerminalExitKind {
2473 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2474 where
2475 D: serde::Deserializer<'de>,
2476 {
2477 let value = String::deserialize(deserializer)?;
2478 Ok(match value.as_str() {
2479 "clean" => Self::Clean,
2480 "crash" => Self::Crash,
2481 "deliberate_severance" => Self::DeliberateSeverance,
2482 _ => Self::Unknown(value),
2483 })
2484 }
2485}
2486
2487open_string_enum! {
2488 TerminalDisposition {
2490 Stopped => "stopped",
2491 Disabled => "disabled",
2492 Failed => "failed",
2493 Restarting => "restarting",
2494 DaemonShutdown => "daemon_shutdown",
2499 }
2500}
2501
2502#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2503#[serde(rename_all = "snake_case")]
2504pub enum PollKind {
2505 Status,
2506 Liveness,
2507}
2508
2509#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2521#[non_exhaustive]
2522pub struct CatalogEntry {
2523 pub module_id: String,
2524 #[serde(default, skip_serializing_if = "Option::is_none")]
2526 pub display_name: Option<String>,
2527 #[serde(default, skip_serializing_if = "Option::is_none")]
2529 pub module_name: Option<String>,
2530 #[serde(default, skip_serializing_if = "Option::is_none")]
2532 pub icon: Option<String>,
2533 #[serde(default, skip_serializing_if = "Option::is_none")]
2536 pub hosts_third_party_code: Option<bool>,
2537 #[serde(default = "default_true")]
2548 pub ready: bool,
2549 #[serde(default, skip_serializing_if = "Option::is_none")]
2553 pub not_ready: Option<NotReadyReason>,
2554 #[serde(default, skip_serializing_if = "Option::is_none")]
2575 pub module_version: Option<String>,
2576 #[serde(default, skip_serializing_if = "Option::is_none")]
2579 pub provenance: Option<ManifestProvenance>,
2580 pub roles: Vec<ProviderRole>,
2581 pub control_ops: Vec<String>,
2582 #[serde(default, skip_serializing_if = "Option::is_none")]
2587 pub capabilities: Option<CapabilityDeclarations>,
2588 #[serde(default, skip_serializing_if = "Option::is_none")]
2591 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2592 #[serde(default, skip_serializing_if = "Option::is_none")]
2596 pub events: Option<Vec<EventDeclaration>>,
2597 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2600 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2601 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2603 pub operation_titles: BTreeMap<String, String>,
2604 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2606 pub operation_groups: BTreeMap<String, OperationGroup>,
2607 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2609 pub operation_requires: BTreeMap<String, Vec<String>>,
2610 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2613 pub operation_payload: BTreeMap<String, OperationPayload>,
2614 #[serde(default, skip_serializing_if = "Option::is_none")]
2620 pub flow_operations: Option<Vec<String>>,
2621 #[serde(default, skip_serializing_if = "Option::is_none")]
2623 pub operation_deferral: Option<BTreeMap<String, bool>>,
2624 #[serde(default, skip_serializing_if = "Option::is_none")]
2630 pub confirm_operations: Option<Vec<String>>,
2631 #[serde(default, skip_serializing_if = "Option::is_none")]
2634 pub rich_ui: Option<RichUiDescriptor>,
2635 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2638 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2639 #[serde(default, skip_serializing_if = "is_false")]
2644 pub nonce_verified: bool,
2645 #[serde(default, skip_serializing_if = "Option::is_none")]
2648 pub incarnation: Option<String>,
2649 #[serde(
2650 default,
2651 skip_serializing_if = "Option::is_none",
2652 deserialize_with = "deserialize_optional_attestation_integer"
2653 )]
2654 pub spawn: Option<u64>,
2655 #[serde(default, skip_serializing_if = "Option::is_none")]
2656 pub first_party: Option<bool>,
2657 #[serde(default, skip_serializing_if = "Option::is_none")]
2658 pub origin: Option<CatalogOrigin>,
2659 #[serde(default, skip_serializing_if = "Option::is_none")]
2660 pub requested_declarations_digest: Option<String>,
2661 #[serde(default, skip_serializing_if = "Option::is_none")]
2662 pub approved_declarations_digest: Option<String>,
2663 #[serde(default, skip_serializing_if = "Option::is_none")]
2665 pub effective_declarations_digest: Option<String>,
2666 #[serde(default, skip_serializing_if = "Option::is_none")]
2669 pub approved_declarations: Option<ProviderDeclarations>,
2670 #[serde(default, skip_serializing_if = "Option::is_none")]
2671 pub requested_declarations: Option<ProviderDeclarations>,
2672 #[serde(default, skip_serializing_if = "Option::is_none")]
2676 pub effective_declarations: Option<ProviderDeclarations>,
2677}
2678
2679impl CatalogEntry {
2680 #[must_use]
2682 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2683 self.display_name = display_name;
2684 self
2685 }
2686
2687 #[must_use]
2689 pub fn with_module_name(mut self, module_name: Option<String>) -> Self {
2690 self.module_name = module_name;
2691 self
2692 }
2693
2694 pub fn with_icon(mut self, icon: Option<String>) -> Self {
2696 self.icon = icon;
2697 self
2698 }
2699
2700 #[must_use]
2702 pub fn new(
2703 module_id: impl Into<String>,
2704 roles: Vec<ProviderRole>,
2705 control_ops: Vec<String>,
2706 ) -> Self {
2707 Self {
2708 module_id: module_id.into(),
2709 ready: default_true(),
2710 display_name: None,
2711 module_name: None,
2712 icon: None,
2713 hosts_third_party_code: None,
2714 not_ready: None,
2715 module_version: None,
2716 provenance: None,
2717 roles,
2718 control_ops,
2719 capabilities: None,
2720 self_signals: None,
2721 events: None,
2722 operation_delivery: BTreeMap::new(),
2723 operation_titles: BTreeMap::new(),
2724 operation_groups: BTreeMap::new(),
2725 operation_requires: BTreeMap::new(),
2726 operation_payload: BTreeMap::new(),
2727 flow_operations: None,
2728 operation_deferral: None,
2729 confirm_operations: None,
2730 rich_ui: None,
2731 role_declarations: BTreeMap::new(),
2732 nonce_verified: false,
2733 incarnation: None,
2734 spawn: None,
2735 first_party: None,
2736 origin: None,
2737 requested_declarations_digest: None,
2738 approved_declarations_digest: None,
2739 effective_declarations_digest: None,
2740 approved_declarations: None,
2741 requested_declarations: None,
2742 effective_declarations: None,
2743 }
2744 }
2745
2746 #[must_use]
2748 pub fn with_operation_payload(
2749 mut self,
2750 operation_payload: BTreeMap<String, OperationPayload>,
2751 ) -> Self {
2752 self.operation_payload = operation_payload;
2753 self
2754 }
2755
2756 #[must_use]
2759 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2760 self.flow_operations = flow_operations;
2761 self
2762 }
2763
2764 #[must_use]
2766 pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
2767 self.operation_deferral = operations;
2768 self
2769 }
2770
2771 #[must_use]
2774 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2775 self.confirm_operations = confirm_operations;
2776 self
2777 }
2778
2779 #[must_use]
2781 pub fn with_ready(mut self, ready: bool) -> Self {
2782 self.ready = ready;
2783 self
2784 }
2785
2786 #[must_use]
2788 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2789 self.not_ready = not_ready;
2790 self
2791 }
2792
2793 #[must_use]
2795 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2796 self.module_version = module_version;
2797 self
2798 }
2799
2800 #[must_use]
2802 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2803 self.provenance = provenance;
2804 self
2805 }
2806
2807 #[must_use]
2809 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2810 self.capabilities = capabilities;
2811 self
2812 }
2813
2814 #[must_use]
2816 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2817 self.self_signals = self_signals;
2818 self
2819 }
2820
2821 #[must_use]
2823 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2824 self.events = events;
2825 self
2826 }
2827
2828 #[must_use]
2831 pub fn with_operation_delivery(
2832 mut self,
2833 operation_delivery: BTreeMap<String, OperationDelivery>,
2834 ) -> Self {
2835 self.operation_delivery = operation_delivery;
2836 self
2837 }
2838
2839 pub fn with_operation_titles(mut self, operation_titles: BTreeMap<String, String>) -> Self {
2841 self.operation_titles = operation_titles;
2842 self
2843 }
2844
2845 pub fn with_operation_groups(
2847 mut self,
2848 operation_groups: BTreeMap<String, OperationGroup>,
2849 ) -> Self {
2850 self.operation_groups = operation_groups;
2851 self
2852 }
2853
2854 pub fn with_operation_requires(
2856 mut self,
2857 operation_requires: BTreeMap<String, Vec<String>>,
2858 ) -> Self {
2859 self.operation_requires = operation_requires;
2860 self
2861 }
2862
2863 #[must_use]
2865 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2866 self.rich_ui = rich_ui;
2867 self
2868 }
2869
2870 #[must_use]
2872 pub fn with_role_declarations(
2873 mut self,
2874 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2875 ) -> Self {
2876 self.role_declarations = role_declarations;
2877 self
2878 }
2879
2880 #[must_use]
2882 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2883 self.nonce_verified = nonce_verified;
2884 self
2885 }
2886}
2887
2888fn is_false(value: &bool) -> bool {
2889 !value
2890}
2891
2892#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2894pub struct NotReadyReason {
2895 pub reason: String,
2900 #[serde(default, skip_serializing_if = "Option::is_none")]
2903 pub capability: Option<String>,
2904}
2905
2906impl NotReadyReason {
2907 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2908 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2909}
2910
2911#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2912pub struct CapabilityRequirementStatus {
2913 pub consumer: String,
2914 pub capability: String,
2915 pub need: String,
2916 pub verdict: String,
2917 pub episode_seq: u64,
2918 pub config_satisfiable: bool,
2919 pub runtime_available: bool,
2920 pub detail: String,
2921}
2922
2923#[non_exhaustive]
2928#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2929#[serde(rename_all = "snake_case")]
2930pub enum PendingModuleApply {
2931 NextSupervision,
2932 WithNextLaunchOrHealthChange,
2933 DaemonRestart,
2934 ConfigGate,
2935 #[serde(other)]
2936 Other,
2937}
2938
2939#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2941pub struct SupervisorPendingField {
2942 pub field: String,
2943 pub applies: PendingModuleApply,
2944 #[serde(default, skip_serializing_if = "Option::is_none")]
2945 pub value: Option<serde_json::Value>,
2946}
2947
2948#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2949pub struct SupervisorPendingModule {
2950 pub module_id: String,
2951 pub fields: Vec<SupervisorPendingField>,
2952}
2953
2954#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2959pub struct SupervisorLiveChange {
2960 pub module_id: String,
2961 pub fields: Vec<String>,
2962}
2963
2964#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2965pub struct SupervisorRescanResult {
2966 pub added: Vec<String>,
2967 pub removed: Vec<String>,
2968 pub changed_pending_reload: Vec<String>,
2969 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2971 pub changed_pending: Vec<SupervisorPendingModule>,
2972 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2974 pub changed_live: Vec<SupervisorLiveChange>,
2975 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2988 pub enabled_changes: Vec<String>,
2989 pub unchanged: u32,
2990 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2998 pub preview: bool,
2999 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3017 pub restart_required: Vec<String>,
3018 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3022 pub capability_warnings: Vec<String>,
3023 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3029 pub module_actions: Vec<RescanModuleAction>,
3030 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3034 pub earlier_pending: Vec<String>,
3035 #[serde(default, skip_serializing_if = "Option::is_none")]
3038 pub expect: Option<RescanExpect>,
3039}
3040
3041#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
3057#[serde(rename_all = "snake_case")]
3058pub enum ModuleProtocol {
3059 #[default]
3063 Subc,
3064 None,
3073}
3074
3075#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3087#[non_exhaustive]
3088pub struct SupervisorEntry {
3089 #[serde(default, skip_serializing_if = "Option::is_none")]
3091 pub script: Option<ScriptModuleStatus>,
3092 #[serde(default, skip_serializing_if = "Option::is_none")]
3095 pub waiting_for_previous_pid: Option<u32>,
3096 #[serde(default, skip_serializing_if = "Option::is_none")]
3099 pub waiting_for_previous_detail: Option<String>,
3100 pub module_id: String,
3101 pub state: String,
3102 #[serde(default, skip_serializing_if = "Option::is_none")]
3104 pub accepting_drain: Option<bool>,
3105 #[serde(default, skip_serializing_if = "Option::is_none")]
3109 pub admission_refused: Option<String>,
3110 #[serde(default, skip_serializing_if = "Option::is_none")]
3114 pub next_retry_at_ms: Option<u64>,
3115 pub enabled: bool,
3116 #[serde(default, skip_serializing_if = "Option::is_none")]
3119 pub configured_enabled: Option<bool>,
3120 pub live: bool,
3130 #[serde(default)]
3134 pub protocol: ModuleProtocol,
3135 #[serde(default, skip_serializing_if = "Option::is_none")]
3138 pub launch_nonce_env: Option<bool>,
3139 #[serde(default, skip_serializing_if = "Option::is_none")]
3145 pub launch_nonce_source: Option<String>,
3146 pub health: SupervisorHealthStatus,
3147 #[serde(default, skip_serializing_if = "Option::is_none")]
3150 pub pending_reload: Option<PendingReloadVerdict>,
3151 #[serde(default)]
3157 pub last_probe_ms: Option<u64>,
3158 #[serde(default, skip_serializing_if = "Option::is_none")]
3162 pub last_exit_code: Option<i32>,
3163 #[serde(default, skip_serializing_if = "Option::is_none")]
3167 pub last_exit_signal: Option<i32>,
3168 #[serde(default, skip_serializing_if = "Option::is_none")]
3172 pub last_exit_ms: Option<u64>,
3173 #[serde(default, skip_serializing_if = "Option::is_none")]
3176 pub last_exit_kind: Option<TerminalExitKind>,
3177 #[serde(default, skip_serializing_if = "Option::is_none")]
3194 pub restart_count: Option<u32>,
3195 #[serde(default, skip_serializing_if = "Option::is_none")]
3198 pub max_restarts: Option<u32>,
3199 #[serde(default, skip_serializing_if = "Option::is_none")]
3202 pub lifetime_restarts: Option<u32>,
3203 #[serde(default, skip_serializing_if = "Option::is_none")]
3207 pub spawn_generation: Option<u64>,
3208 #[serde(default, skip_serializing_if = "Option::is_none")]
3218 pub restart_window_secs: Option<u64>,
3219 #[serde(default, skip_serializing_if = "Option::is_none")]
3223 pub drain_timeout_ms: Option<u64>,
3224 #[serde(default, skip_serializing_if = "Option::is_none")]
3227 pub restart_backoff_ms: Option<u64>,
3228 #[serde(default, skip_serializing_if = "Option::is_none")]
3231 pub restart_max_backoff_ms: Option<u64>,
3232 #[serde(default, skip_serializing_if = "Option::is_none")]
3245 pub resources: Option<ChildResourceUsage>,
3246 #[serde(default, skip_serializing_if = "Option::is_none")]
3248 pub tree: Option<TreeReading>,
3249 #[serde(default, skip_serializing_if = "Option::is_none")]
3255 pub tree_unavailable: Option<String>,
3256 #[serde(default, skip_serializing_if = "Option::is_none")]
3258 pub cpu_last_hour: Option<CpuLastHour>,
3259 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3261 pub pending: Vec<SupervisorPendingField>,
3262}
3263
3264impl SupervisorEntry {
3265 #[must_use]
3266 pub fn with_script(mut self, script: Option<ScriptModuleStatus>) -> Self {
3267 self.script = script;
3268 self
3269 }
3270 #[must_use]
3272 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3273 self.next_retry_at_ms = next_retry_at_ms;
3274 self
3275 }
3276
3277 #[must_use]
3279 pub fn new(
3280 module_id: impl Into<String>,
3281 state: impl Into<String>,
3282 enabled: bool,
3283 live: bool,
3284 health: SupervisorHealthStatus,
3285 ) -> Self {
3286 Self {
3287 module_id: module_id.into(),
3288 script: None,
3289 state: state.into(),
3290 admission_refused: None,
3291 next_retry_at_ms: None,
3292 waiting_for_previous_pid: None,
3293 waiting_for_previous_detail: None,
3294 accepting_drain: None,
3295 enabled,
3296 configured_enabled: None,
3297 live,
3298 protocol: ModuleProtocol::default(),
3299 launch_nonce_env: None,
3300 launch_nonce_source: None,
3301 health,
3302 pending_reload: None,
3303 last_probe_ms: None,
3304 last_exit_code: None,
3305 last_exit_signal: None,
3306 last_exit_ms: None,
3307 last_exit_kind: None,
3308 restart_count: None,
3309 max_restarts: None,
3310 lifetime_restarts: None,
3311 spawn_generation: None,
3312 restart_window_secs: None,
3313 drain_timeout_ms: None,
3314 restart_backoff_ms: None,
3315 restart_max_backoff_ms: None,
3316 resources: None,
3317 tree: None,
3318 tree_unavailable: None,
3319 cpu_last_hour: None,
3320 pending: Vec::new(),
3321 }
3322 }
3323
3324 #[must_use]
3326 pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3327 self.admission_refused = reason;
3328 self
3329 }
3330
3331 #[must_use]
3333 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3334 self.protocol = protocol;
3335 self
3336 }
3337
3338 #[must_use]
3340 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3341 self.configured_enabled = configured_enabled;
3342 self
3343 }
3344
3345 #[must_use]
3347 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3348 self.launch_nonce_env = launch_nonce_env;
3349 self
3350 }
3351
3352 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3353 self.launch_nonce_source = source;
3354 self
3355 }
3356
3357 #[must_use]
3358 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3359 self.waiting_for_previous_pid = pid;
3360 self
3361 }
3362
3363 #[must_use]
3364 pub fn with_waiting_for_previous_detail(mut self, detail: Option<String>) -> Self {
3365 self.waiting_for_previous_detail = detail;
3366 self
3367 }
3368
3369 #[must_use]
3371 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3372 self.pending_reload = pending_reload;
3373 self
3374 }
3375
3376 #[must_use]
3378 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3379 self.last_probe_ms = last_probe_ms;
3380 self
3381 }
3382
3383 #[must_use]
3385 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3386 self.last_exit_code = last_exit_code;
3387 self
3388 }
3389
3390 #[must_use]
3392 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3393 self.last_exit_signal = last_exit_signal;
3394 self
3395 }
3396
3397 #[must_use]
3399 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3400 self.last_exit_ms = last_exit_ms;
3401 self
3402 }
3403
3404 #[must_use]
3406 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3407 self.last_exit_kind = last_exit_kind;
3408 self
3409 }
3410
3411 #[must_use]
3413 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3414 self.restart_count = restart_count;
3415 self
3416 }
3417
3418 #[must_use]
3420 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3421 self.max_restarts = max_restarts;
3422 self
3423 }
3424
3425 #[must_use]
3427 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3428 self.lifetime_restarts = lifetime_restarts;
3429 self
3430 }
3431
3432 #[must_use]
3434 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3435 self.spawn_generation = spawn_generation;
3436 self
3437 }
3438
3439 #[must_use]
3441 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3442 self.restart_window_secs = restart_window_secs;
3443 self
3444 }
3445
3446 #[must_use]
3448 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3449 self.drain_timeout_ms = drain_timeout_ms;
3450 self
3451 }
3452
3453 #[must_use]
3455 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3456 self.restart_backoff_ms = restart_backoff_ms;
3457 self
3458 }
3459
3460 #[must_use]
3462 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3463 self.restart_max_backoff_ms = restart_max_backoff_ms;
3464 self
3465 }
3466
3467 #[must_use]
3469 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3470 self.resources = resources;
3471 self
3472 }
3473
3474 #[must_use]
3476 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3477 self.tree = tree;
3478 self
3479 }
3480
3481 #[must_use]
3483 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3484 self.tree_unavailable = reason;
3485 self
3486 }
3487}
3488
3489#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3491pub struct ScriptModuleStatus {
3492 pub runtime: String,
3493 pub bun_version: Option<String>,
3494 pub path: PathBuf,
3495 pub sha256: Option<String>,
3496 pub size: Option<u64>,
3497 pub needs_review: bool,
3498}
3499
3500#[cfg(test)]
3501mod script_status_tests {
3502 use super::*;
3503
3504 #[test]
3505 fn script_status_roundtrips_and_old_supervisor_entries_remain_readable() {
3506 let old = SupervisorEntry::new(
3507 "example",
3508 "running",
3509 true,
3510 true,
3511 SupervisorHealthStatus::Unknown,
3512 );
3513 let value = serde_json::to_value(&old).unwrap();
3514 assert!(value.get("script").is_none());
3515 assert!(serde_json::from_value::<SupervisorEntry>(value)
3516 .unwrap()
3517 .script
3518 .is_none());
3519 let current = old.with_script(Some(ScriptModuleStatus {
3520 runtime: "bun".into(),
3521 bun_version: None,
3522 path: "bundle.js".into(),
3523 sha256: Some("ab".repeat(32)),
3524 size: Some(3),
3525 needs_review: true,
3526 }));
3527 let decoded: SupervisorEntry =
3528 serde_json::from_slice(&serde_json::to_vec(¤t).unwrap()).unwrap();
3529 assert_eq!(decoded, current);
3530 }
3531}
3532
3533#[derive(Debug, Clone, PartialEq)]
3536pub enum ChildResourceUsage {
3537 Measured(ChildResourceReading),
3538 Unavailable {
3539 reason: ChildResourceUnavailableReason,
3540 },
3541 Unknown {
3544 tag: String,
3545 body: OrderedJsonObject,
3546 },
3547}
3548
3549#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3552#[non_exhaustive]
3553pub struct ChildResourceReading {
3554 pub memory_bytes: u64,
3557 pub memory_kind: ChildMemoryKind,
3558 #[serde(default, skip_serializing_if = "Option::is_none")]
3561 pub swap_bytes: Option<u64>,
3562 pub cpu_user_ms: u64,
3566 pub cpu_system_ms: u64,
3569}
3570
3571impl ChildResourceReading {
3572 #[must_use]
3574 pub fn new(
3575 memory_bytes: u64,
3576 memory_kind: ChildMemoryKind,
3577 cpu_user_ms: u64,
3578 cpu_system_ms: u64,
3579 ) -> Self {
3580 Self {
3581 memory_bytes,
3582 memory_kind,
3583 cpu_user_ms,
3584 cpu_system_ms,
3585 swap_bytes: None,
3586 }
3587 }
3588
3589 #[must_use]
3591 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3592 self.swap_bytes = swap_bytes;
3593 self
3594 }
3595}
3596
3597open_string_enum! {
3598 ChildMemoryKind {
3600 PhysFootprint => "phys_footprint",
3604 ResidentSet => "resident_set",
3607 WindowsWorkingSet => "windows_working_set",
3610 }
3611}
3612
3613open_string_enum! {
3614 ChildResourceUnavailableReason {
3616 NotRunning => "not_running",
3618 UnsupportedPlatform => "unsupported_platform",
3620 Unreadable => "unreadable",
3623 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3626 }
3627}
3628
3629#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3630#[serde(rename_all = "snake_case")]
3631pub enum SupervisorHealthStatus {
3632 Ok,
3633 Degraded,
3634 Failing,
3635 Unresponsive,
3636 Unknown,
3637}
3638
3639impl SupervisorHealthStatus {
3640 pub fn plain_line(self) -> &'static str {
3645 match self {
3646 Self::Ok => "Running normally",
3647 Self::Degraded => "Working, with a problem",
3648 Self::Failing => "Not working",
3649 Self::Unresponsive => "Not responding",
3650 Self::Unknown => "No health report",
3651 }
3652 }
3653}
3654
3655impl SupervisorHealthEntry {
3656 pub fn readable_line(&self) -> &str {
3660 self.summary
3661 .as_deref()
3662 .unwrap_or_else(|| self.status.plain_line())
3663 }
3664}
3665
3666#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3667pub struct SupervisorHealthEntry {
3668 pub module_id: String,
3669 pub status: SupervisorHealthStatus,
3670 #[serde(default, skip_serializing_if = "Option::is_none")]
3676 pub detail: Option<String>,
3677 #[serde(default, skip_serializing_if = "Option::is_none")]
3683 pub summary: Option<String>,
3684 #[serde(default, skip_serializing_if = "Option::is_none")]
3689 pub metrics: Option<serde_json::Value>,
3690 pub consecutive_failures: u32,
3691 #[serde(default)]
3694 pub late_answer_count: u64,
3695 #[serde(default, skip_serializing_if = "Option::is_none")]
3697 pub last_late_answer_latency_ms: Option<u64>,
3698 #[serde(default)]
3703 pub last_action: Option<String>,
3704 #[serde(default)]
3707 pub last_action_ms: Option<u64>,
3708 #[serde(default, skip_serializing_if = "Option::is_none")]
3721 pub last_probe_ms: Option<u64>,
3722}
3723
3724#[cfg(test)]
3725mod tests {
3726 #[test]
3727 fn health_entry_readable_line_prefers_summary_then_fixed_status_line() {
3728 use super::{SupervisorHealthEntry, SupervisorHealthStatus as S};
3729 let entry: SupervisorHealthEntry = serde_json::from_str(
3730 r#"{"module_id":"m","status":"degraded","detail":"queue {\"depth\":3}","consecutive_failures":0}"#,
3731 )
3732 .unwrap();
3733 assert_eq!(entry.readable_line(), "Working, with a problem");
3734 let entry = SupervisorHealthEntry {
3735 summary: Some("Replies are slow right now.".into()),
3736 ..entry
3737 };
3738 assert_eq!(entry.readable_line(), "Replies are slow right now.");
3739 for (status, line) in [
3740 (S::Ok, "Running normally"),
3741 (S::Degraded, "Working, with a problem"),
3742 (S::Failing, "Not working"),
3743 (S::Unresponsive, "Not responding"),
3744 (S::Unknown, "No health report"),
3745 ] {
3746 assert_eq!(status.plain_line(), line);
3747 }
3748 }
3749
3750 #[test]
3751 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3752 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3753 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3754 assert_eq!(decoded.configured_enabled, None);
3755 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3756 }
3757
3758 #[test]
3759 fn configured_enabled_values_round_trip_in_list() {
3760 for enabled in [false, true] {
3761 let entry = SupervisorEntry::new(
3762 "provider",
3763 "running",
3764 true,
3765 true,
3766 SupervisorHealthStatus::Unknown,
3767 )
3768 .with_configured_enabled(Some(enabled));
3769 let entry_json = serde_json::to_value(&entry).unwrap();
3770 assert_eq!(entry_json["configured_enabled"], enabled);
3771 assert_eq!(
3772 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3773 entry
3774 );
3775 }
3776 }
3777
3778 #[test]
3779 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3780 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3781 volume_serial_number: u64::MAX,
3782 file_id: [
3783 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3784 ],
3785 };
3786 let agreement = super::RunningImageAgreement::Match { evidence };
3787 let encoded = serde_json::to_string(&agreement).unwrap();
3788 assert!(encoded.contains("windows_spawn_file_id"));
3789 assert_eq!(
3790 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3791 agreement
3792 );
3793 }
3794
3795 #[test]
3796 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3797 assert_eq!(
3798 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3799 device: 7,
3800 inode: 11
3801 })
3802 .unwrap(),
3803 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3804 );
3805 assert_eq!(
3806 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3807 digest: "abc".to_owned()
3808 })
3809 .unwrap(),
3810 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3811 );
3812 }
3813 use super::*;
3814 use subc_protocol::{BindIdentity, RouteTarget};
3815
3816 #[test]
3817 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3818 let entry = TerminalEntry {
3819 daemon_incarnation: Some("daemon-before-restart".into()),
3820 exit_code: Some(1),
3821 exit_signal: None,
3822 at_ms: 1_700_000_000_123,
3823 disposition: TerminalDisposition::Restarting,
3824 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3825 disposition_detail: None,
3826 };
3827 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3828 assert_eq!(
3829 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3830 ["exit_kind"],
3831 "deliberate_severance"
3832 );
3833
3834 #[derive(serde::Deserialize)]
3835 struct LegacyTerminalEntry {
3836 exit_code: Option<i32>,
3837 exit_signal: Option<i32>,
3838 at_ms: u64,
3839 disposition: TerminalDisposition,
3840 }
3841
3842 let decoded: LegacyTerminalEntry =
3843 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3844 assert_eq!(decoded.exit_code, Some(1));
3845 assert_eq!(decoded.exit_signal, None);
3846 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3847 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3848
3849 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3850 let future: TerminalEntry =
3851 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3852 assert_eq!(
3853 future.exit_kind,
3854 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3855 );
3856 }
3857
3858 #[test]
3859 fn terminal_incarnation_is_optional_for_older_daemons() {
3860 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3861 "at_ms": 123,
3862 "disposition": "stopped"
3863 }))
3864 .unwrap();
3865 let encoded = serde_json::to_value(&entry).unwrap();
3866 assert_eq!(
3867 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3868 (None, None)
3869 );
3870 }
3871
3872 #[test]
3873 fn route_poll_uses_kind_field() {
3874 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3875 route_channel: 7,
3876 route_epoch: 11,
3877 kind: PollKind::Status,
3878 })
3879 .unwrap();
3880
3881 assert_eq!(body["op"], "route.poll");
3882 assert_eq!(body["route_epoch"], 11);
3883 assert_eq!(body["kind"], "status");
3884 assert!(body.get("op").is_some());
3885 }
3886
3887 #[test]
3888 fn route_open_is_internally_tagged() {
3889 let request = ClientControlRequest::RouteOpen {
3890 busy_refusals: None,
3891 target: RouteTarget::ToolProvider {
3892 module_id: "aft".to_string(),
3893 },
3894 identity: BindIdentity::new("opencode", "session-1"),
3895 consumer_identity: None,
3896 consumer_capabilities: None,
3897 role_versions: None,
3898 admission_facts: None,
3899 scope: None,
3900 };
3901
3902 let body = serde_json::to_value(request).unwrap();
3903 assert_eq!(body["op"], "route.open");
3904 assert_eq!(body["target"]["kind"], "tool_provider");
3905 assert!(body.get("consumer_identity").is_none());
3906 assert!(body.get("consumer_capabilities").is_none());
3907 assert!(body.get("role_versions").is_none());
3908 }
3909
3910 #[test]
3911 fn route_open_without_optional_fields_still_decodes() {
3912 let body = serde_json::json!({
3913 "op": "route.open",
3914 "target": { "kind": "tool_provider", "module_id": "aft" },
3915 "identity": {
3916 "project_root": "/tmp/project",
3917 "harness": "opencode",
3918 "session": "session-1"
3919 }
3920 });
3921
3922 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3923 let ClientControlRequest::RouteOpen {
3924 consumer_identity,
3925 consumer_capabilities,
3926 role_versions,
3927 admission_facts,
3928 ..
3929 } = decoded
3930 else {
3931 panic!("decoded wrong request variant");
3932 };
3933 assert_eq!(consumer_identity, None);
3934 assert_eq!(consumer_capabilities, None);
3935 assert_eq!(role_versions, None);
3936 assert_eq!(admission_facts, None);
3937 }
3938
3939 #[test]
3940 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3941 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3942 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3943 match decoded {
3944 ClientControlPush::RouteClosed {
3945 excluded_subscriptions,
3946 terminal,
3947 ..
3948 } => {
3949 assert_eq!(excluded_subscriptions, 0);
3950 assert_eq!(terminal, None);
3951 }
3952 other => panic!("unexpected push: {other:?}"),
3953 }
3954 assert!(!serde_json::to_string(&decoded)
3955 .unwrap()
3956 .contains("terminal"));
3957 }
3958
3959 #[test]
3960 fn old_route_closed_decoder_ignores_new_terminal_field() {
3961 #[derive(serde::Deserialize)]
3962 #[serde(tag = "op")]
3963 enum LegacyClientControlPush {
3964 #[serde(rename = "route.closed")]
3965 RouteClosed {
3966 module_id: String,
3967 reason: RouteCloseReason,
3968 drained: bool,
3969 abandoned: u32,
3970 },
3971 }
3972
3973 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3974 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3975 match decoded {
3976 LegacyClientControlPush::RouteClosed {
3977 module_id,
3978 reason,
3979 drained,
3980 abandoned,
3981 } => {
3982 assert_eq!(module_id, "aft-tools");
3983 assert_eq!(reason, RouteCloseReason::Crash);
3984 assert!(!drained);
3985 assert_eq!(abandoned, 0);
3986 }
3987 }
3988 }
3989
3990 #[test]
3991 fn supervisor_routes_is_a_control_plane_request() {
3992 let body = serde_json::json!({
3993 "op": "supervisor.routes",
3994 "module_id": "aft"
3995 });
3996
3997 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3998 assert_eq!(serde_json::to_value(request).unwrap(), body);
3999 }
4000
4001 #[test]
4002 fn diagnostic_string_enums_retain_unknown_wire_values() {
4003 let reason: RunningImageUnavailableReason =
4004 serde_json::from_str("\"future_reason\"").unwrap();
4005 let disposition: TerminalDisposition =
4006 serde_json::from_str("\"future_disposition\"").unwrap();
4007
4008 assert_eq!(
4009 reason,
4010 RunningImageUnavailableReason::Unknown("future_reason".to_string())
4011 );
4012 assert_eq!(
4013 disposition,
4014 TerminalDisposition::Unknown("future_disposition".to_string())
4015 );
4016 }
4017
4018 #[test]
4019 fn diagnostic_string_enums_preserve_existing_wire_names() {
4020 let names = [
4021 (RunningImageUnavailableReason::NotRunning, "not_running"),
4022 (
4023 RunningImageUnavailableReason::UnsupportedPlatform,
4024 "unsupported_platform",
4025 ),
4026 (
4027 RunningImageUnavailableReason::RunningExecutableUnreadable,
4028 "running_executable_unreadable",
4029 ),
4030 (
4031 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
4032 "running_executable_permission_denied",
4033 ),
4034 (
4035 RunningImageUnavailableReason::ProcessHidden,
4036 "process_hidden",
4037 ),
4038 (
4039 RunningImageUnavailableReason::SpawnedPathUnreadable,
4040 "spawned_path_unreadable",
4041 ),
4042 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
4043 (
4044 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
4045 "process_identity_unconfirmed",
4046 ),
4047 ];
4048 for (value, expected) in names {
4049 let wire = serde_json::to_string(&value).unwrap();
4050 assert_eq!(wire, format!("\"{expected}\""));
4051 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
4052 assert_eq!(decoded, value);
4053 }
4054
4055 for (value, expected) in [
4056 (TerminalDisposition::Stopped, "stopped"),
4057 (TerminalDisposition::Disabled, "disabled"),
4058 (TerminalDisposition::Failed, "failed"),
4059 (TerminalDisposition::Restarting, "restarting"),
4060 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
4061 ] {
4062 let wire = serde_json::to_string(&value).unwrap();
4063 assert_eq!(wire, format!("\"{expected}\""));
4064 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
4065 assert_eq!(decoded, value);
4066 }
4067 }
4068
4069 #[test]
4070 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
4071 let entry = SupervisorEntry::new(
4072 "waiting-module",
4073 "starting",
4074 true,
4075 false,
4076 SupervisorHealthStatus::Unknown,
4077 );
4078 let old_wire = serde_json::to_value(&entry).unwrap();
4079 assert!(old_wire.get("waiting_for_previous_pid").is_none());
4080 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
4081 assert_eq!(decoded.waiting_for_previous_pid, None);
4082 let entry = entry.with_waiting_for_previous_pid(Some(42));
4083 let wire = serde_json::to_value(&entry).unwrap();
4084 assert_eq!(wire["waiting_for_previous_pid"], 42);
4085 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
4086 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
4087 }
4088
4089 #[test]
4090 fn supervisor_waiting_previous_detail_is_optional_and_round_trips() {
4091 let entry = SupervisorEntry::new(
4092 "worker",
4093 "starting",
4094 true,
4095 false,
4096 SupervisorHealthStatus::Unknown,
4097 )
4098 .with_waiting_for_previous_pid(Some(41));
4099 let old_wire = serde_json::to_value(&entry).unwrap();
4100 assert!(old_wire.get("waiting_for_previous_detail").is_none());
4101 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
4102 assert_eq!(decoded.waiting_for_previous_detail, None);
4103 let detail = "waiting: container survivors (pids [42])";
4104 let wire =
4105 serde_json::to_value(entry.with_waiting_for_previous_detail(Some(detail.into())))
4106 .unwrap();
4107 assert_eq!(wire["waiting_for_previous_pid"], 41);
4108 assert_eq!(wire["waiting_for_previous_detail"], detail);
4109 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
4110 assert_eq!(decoded.waiting_for_previous_detail.as_deref(), Some(detail));
4111 }
4112
4113 #[test]
4114 fn diagnostic_string_enums_reject_non_string_bodies() {
4115 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
4116 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
4117 }
4118
4119 #[test]
4120 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
4121 let body = serde_json::json!({
4122 "op": "supervisor.provenance",
4123 "daemon": {
4124 "daemon_build": {},
4125 "daemon_observed": {
4126 "running_image": {
4127 "status": "unavailable",
4128 "reason": "not_running"
4129 }
4130 }
4131 },
4132 "modules": [
4133 {
4134 "module_id": "future",
4135 "module_declared": { "status": "unverifiable" },
4136 "daemon_observed": {
4137 "running_image": {
4138 "status": "unavailable",
4139 "reason": "future_reason"
4140 }
4141 }
4142 },
4143 {
4144 "module_id": "healthy-a",
4145 "module_declared": { "status": "unverifiable" },
4146 "daemon_observed": {
4147 "running_image": {
4148 "status": "match",
4149 "evidence": {
4150 "method": "linux_proc_sha256",
4151 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
4152 }
4153 }
4154 }
4155 },
4156 {
4157 "module_id": "healthy-b",
4158 "module_declared": { "status": "unverifiable" },
4159 "daemon_observed": {
4160 "running_image": {
4161 "status": "unavailable",
4162 "reason": "unsupported_platform"
4163 }
4164 }
4165 }
4166 ]
4167 });
4168
4169 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
4170 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
4171 panic!("decoded wrong response variant");
4172 };
4173 assert_eq!(modules.len(), 3);
4174 assert_eq!(modules[0].module_id, "future");
4175 assert_eq!(
4176 modules[0].daemon_observed.running_image,
4177 RunningImageAgreement::Unavailable {
4178 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
4179 }
4180 );
4181 assert_eq!(modules[1].module_id, "healthy-a");
4182 assert_eq!(modules[2].module_id, "healthy-b");
4183 }
4184
4185 #[test]
4186 fn tagged_unknown_values_retain_tag_and_body() {
4187 macro_rules! assert_unknown_round_trip {
4188 ($ty:ident, $field:literal, $value:expr) => {
4189 let value = $value;
4190 let wire = serde_json::to_string(&value).unwrap();
4191 let decoded: $ty = serde_json::from_str(&wire).unwrap();
4192 match decoded {
4193 $ty::Unknown { tag, body } => {
4194 assert_eq!(tag, value[$field].as_str().unwrap());
4195 assert_eq!(serde_json::to_value(&body).unwrap(), value);
4196 }
4197 _ => panic!("decoded known variant"),
4198 }
4199 };
4200 }
4201
4202 assert_unknown_round_trip!(
4203 ModuleDeclaredProvenance,
4204 "status",
4205 serde_json::json!({"status": "future", "build": {"version": 7}})
4206 );
4207 assert_unknown_round_trip!(
4208 RunningImageAgreement,
4209 "status",
4210 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
4211 );
4212 assert_unknown_round_trip!(
4213 RunningImageEvidence,
4214 "method",
4215 serde_json::json!({"method": "future", "digest": "abc"})
4216 );
4217 assert_unknown_round_trip!(
4218 SupervisorRouteConsumer,
4219 "kind",
4220 serde_json::json!({"kind": "future", "module_id": "m"})
4221 );
4222 assert_unknown_round_trip!(
4223 StderrCaptureState,
4224 "state",
4225 serde_json::json!({"state": "future", "reason": "because"})
4226 );
4227 assert_unknown_round_trip!(
4228 StderrTailEntry,
4229 "kind",
4230 serde_json::json!({"kind": "future", "text": "line"})
4231 );
4232 assert_unknown_round_trip!(
4233 ChildResourceUsage,
4234 "status",
4235 serde_json::json!({"status": "future", "memory_bytes": 1})
4236 );
4237 }
4238
4239 #[test]
4240 fn child_resource_usage_round_trips_both_known_states() {
4241 let measured = ChildResourceUsage::Measured(ChildResourceReading {
4242 memory_bytes: 0,
4243 memory_kind: ChildMemoryKind::ResidentSet,
4244 swap_bytes: Some(0),
4245 cpu_user_ms: 0,
4246 cpu_system_ms: 0,
4247 });
4248 let wire = serde_json::to_value(&measured).unwrap();
4249 assert_eq!(
4250 wire,
4251 serde_json::json!({
4252 "status": "measured",
4253 "memory_bytes": 0,
4254 "memory_kind": "resident_set",
4255 "swap_bytes": 0,
4256 "cpu_user_ms": 0,
4257 "cpu_system_ms": 0
4258 })
4259 );
4260 assert_eq!(
4261 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4262 measured
4263 );
4264
4265 let unavailable = ChildResourceUsage::Unavailable {
4266 reason: ChildResourceUnavailableReason::NotRunning,
4267 };
4268 let wire = serde_json::to_value(&unavailable).unwrap();
4269 assert_eq!(
4270 wire,
4271 serde_json::json!({"status": "unavailable", "reason": "not_running"})
4272 );
4273 assert_eq!(
4274 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4275 unavailable
4276 );
4277 }
4278
4279 #[test]
4280 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
4281 let stamped: StderrTailEntry = serde_json::from_str(
4285 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
4286 )
4287 .unwrap();
4288 assert_eq!(
4289 stamped,
4290 StderrTailEntry::Line {
4291 text: "boom".to_string(),
4292 truncated: true,
4293 at_ms: Some(1_789_801_440_685),
4294 }
4295 );
4296 let unstamped: StderrTailEntry =
4297 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
4298 assert_eq!(
4299 unstamped,
4300 StderrTailEntry::Line {
4301 text: "boom".to_string(),
4302 truncated: false,
4303 at_ms: None,
4304 }
4305 );
4306 assert_eq!(
4309 serde_json::to_string(&unstamped).unwrap(),
4310 r#"{"kind":"line","text":"boom"}"#
4311 );
4312 assert_eq!(
4313 serde_json::to_value(&stamped).unwrap()["at_ms"],
4314 serde_json::json!(1_789_801_440_685u64)
4315 );
4316 }
4317
4318 #[test]
4319 fn tagged_unknown_values_round_trip_the_original_json() {
4320 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
4321 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4322 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4323 }
4324
4325 #[test]
4326 fn tagged_unknown_values_round_trip_trailing_tag() {
4327 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
4328 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4329 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4330
4331 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
4332 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4333 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4334 }
4335
4336 #[test]
4337 fn tagged_unknown_values_round_trip_middle_tag() {
4338 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
4339 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4340 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4341
4342 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
4343 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4344 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4345 }
4346
4347 #[test]
4348 fn tagged_unknown_values_round_trip_deep_payload() {
4349 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
4350 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4351 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4352
4353 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
4354 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4355 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4356 }
4357
4358 #[test]
4359 fn tagged_unknown_values_reject_non_object_bodies() {
4360 for wire in ["42", r#""future""#, "[]"] {
4361 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
4362 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
4363 }
4364 }
4365
4366 #[test]
4367 fn duplicate_discriminators_reject_without_panicking() {
4368 assert_eq!(
4369 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
4370 .unwrap(),
4371 ModuleDeclaredProvenance::Unverifiable
4372 );
4373 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
4374 .unwrap()
4375 {
4376 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
4377 _ => panic!("future discriminator decoded as a known variant"),
4378 }
4379
4380 let wires = [
4381 r#"{"status":"reported","status":"unverifiable"}"#,
4382 r#"{"status":"unverifiable","status":"reported"}"#,
4383 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4384 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4385 ];
4386
4387 for wire in wires {
4388 let result =
4389 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4390 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4391 assert!(
4392 result.unwrap().is_err(),
4393 "duplicate discriminator decoded: {wire}"
4394 );
4395 }
4396
4397 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4398 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4399 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4400 assert!(
4401 result.unwrap().is_err(),
4402 "duplicate discriminator decoded: {wire}"
4403 );
4404 }
4405
4406 #[test]
4407 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4408 let known_wire =
4409 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4410 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4411 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4412
4413 for wire in [
4414 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4415 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4416 ] {
4417 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4418 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4419 }
4420
4421 for wire in [
4422 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4423 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4424 ] {
4425 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4426 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4427 }
4428
4429 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4430 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4431 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4432
4433 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4434 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4435 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4436 }
4437
4438 #[test]
4439 fn tagged_unknown_member_does_not_discard_known_siblings() {
4440 let body = serde_json::json!({
4441 "modules": [{
4442 "module_id": "target",
4443 "routes": [
4444 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4445 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4446 ]
4447 }]
4448 });
4449 let decoded: ClientControlResponse = serde_json::from_value(
4450 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4451 )
4452 .unwrap();
4453 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4454 panic!("decoded wrong response variant");
4455 };
4456 assert_eq!(modules[0].routes.len(), 2);
4457 assert_eq!(
4458 modules[0].routes[1].consumer,
4459 SupervisorRouteConsumer::Direct { connection_id: 7 }
4460 );
4461 }
4462}
4463
4464#[cfg(test)]
4465mod launch_nonce_redaction_tests {
4466 use super::*;
4467
4468 const NONCE: &str = "nonce-f00dfeed1234abcd";
4469
4470 fn identity() -> ConsumerIdentity {
4471 ConsumerIdentity {
4472 module_id: "wernicke".to_string(),
4473 launch_nonce: NONCE.to_string(),
4474 }
4475 }
4476
4477 #[test]
4478 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4479 let printed = format!("{:?}", identity());
4480 assert!(printed.contains("wernicke"), "{printed}");
4481 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4482 }
4483
4484 #[test]
4485 fn route_open_request_debug_never_prints_the_nonce() {
4486 let request = ClientControlRequest::RouteOpen {
4487 busy_refusals: None,
4488 target: subc_protocol::RouteTarget::ToolProvider {
4489 module_id: "broca".to_string(),
4490 },
4491 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4492 consumer_identity: Some(identity()),
4493 consumer_capabilities: None,
4494 role_versions: None,
4495 admission_facts: None,
4496 scope: None,
4497 };
4498 let printed = format!("{request:?}");
4499 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4500 }
4501}
4502
4503#[cfg(test)]
4504mod reader_skew_tests {
4505 use super::*;
4506 use serde_json::{json, Value};
4507
4508 fn catalog() -> Value {
4509 json!({"module_id": "provider", "roles": [], "control_ops": []})
4510 }
4511
4512 fn reply() -> Value {
4513 json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4514 }
4515
4516 fn target() -> Value {
4517 json!({
4518 "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4519 "authority_epoch": 23, "first_party": true,
4520 "approved_declarations_digest": "approved"
4521 })
4522 }
4523
4524 fn request() -> Value {
4525 json!({
4526 "op": "route.open",
4527 "target": {"kind": "tool_provider", "module_id": "provider"},
4528 "identity": {"harness": "test", "session": "session-1"}
4529 })
4530 }
4531
4532 #[test]
4533 fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4534 let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4535 let built = CatalogEntry::new("provider", vec![], vec![]);
4536 assert_eq!(old, built);
4537 assert_eq!(old.first_party, None);
4538 assert_eq!(old.hosts_third_party_code, None);
4539 assert_eq!(old.effective_declarations_digest, None);
4540 assert_eq!(old.effective_declarations, None);
4541 let old_bytes = serde_json::to_value(&old).unwrap();
4542 let additions = json!({
4543 "incarnation": "daemon", "spawn": 17, "first_party": false,
4544 "origin": "development", "requested_declarations_digest": "requested",
4545 "approved_declarations_digest": "approved", "hosts_third_party_code": false,
4546 "effective_declarations_digest": "requested"
4547 });
4548 let mut body = catalog();
4549 for (key, value) in additions.as_object().unwrap() {
4550 assert!(old_bytes.get(key).is_none(), "{key}");
4551 body[key] = value.clone();
4552 }
4553 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4554 let encoded = serde_json::to_value(&decoded).unwrap();
4555 for (key, value) in additions.as_object().unwrap() {
4556 assert_eq!(&encoded[key], value, "{key}");
4557 }
4558 assert_eq!(decoded.first_party, Some(false));
4559 assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4560 }
4561
4562 #[test]
4563 fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4564 let mut body = catalog();
4565 body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4566 body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4567 body["effective_declarations"] = body["requested_declarations"].clone();
4568 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4569 let encoded = serde_json::to_value(decoded).unwrap();
4570 for key in [
4571 "requested_declarations",
4572 "approved_declarations",
4573 "effective_declarations",
4574 ] {
4575 assert_eq!(encoded[key], body[key]);
4576 }
4577 let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4578 assert_eq!(unfiltered.approved_declarations, None);
4579 assert_eq!(unfiltered.requested_declarations, None);
4580 assert_eq!(unfiltered.effective_declarations, None);
4581 }
4582
4583 #[test]
4584 fn reader_skew_catalog_unknown_origin_is_other() {
4585 let mut body = catalog();
4586 body["origin"] = json!("future-origin");
4587 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4588 assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4589 }
4590
4591 #[test]
4592 fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4593 let mut body = catalog();
4594 body["spawn"] = json!(9_007_199_254_740_991_u64);
4595 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4596 assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4597 for invalid in [
4598 json!(9_007_199_254_740_992_u64),
4599 json!(-1),
4600 json!(1.5),
4601 json!("17"),
4602 ] {
4603 body["spawn"] = invalid;
4604 assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4605 }
4606 }
4607
4608 #[test]
4609 fn reader_skew_catalog_watch_request_uses_subscription_op() {
4610 let body = json!({"op": "catalog.watch"});
4611 let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4612 assert_eq!(request, CatalogWatchRequest::new());
4613 assert_eq!(serde_json::to_value(request).unwrap(), body);
4614 assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4615 for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4616 assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4617 }
4618 }
4619
4620 #[test]
4621 fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4622 for generation in [0, 19, 42] {
4623 let body = json!({"op": "catalog.watch", "generation": generation});
4624 let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4625 assert_eq!(push, CatalogWatchResponse::new(generation));
4626 assert_eq!(serde_json::to_value(push).unwrap(), body);
4627 }
4628 assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4629 for invalid in [
4630 json!({"op": "catalog.watch"}),
4631 json!({"op": "activity.subscribe", "generation": 1}),
4632 ] {
4633 assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4634 }
4635 }
4636
4637 #[test]
4638 fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4639 let mut body = reply();
4640 let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4641 let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4642 assert_eq!(empty, RouteOpenReplyExt::new());
4643 empty.write_to(&mut body).unwrap();
4644 assert_eq!(body, reply());
4645 body["target"] = target();
4646 let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4647 assert_eq!(
4648 decoded.target.as_ref().unwrap().kind,
4649 RouteOpenTargetKind::Spawn
4650 );
4651 let mut encoded = reply();
4652 RouteOpenReplyExt::new()
4653 .with_target(decoded.target)
4654 .write_to(&mut encoded)
4655 .unwrap();
4656 assert_eq!(encoded, body);
4657 assert_eq!(
4658 serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4659 legacy
4660 );
4661 RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4662 assert_eq!(encoded, reply());
4663 }
4664
4665 #[test]
4666 fn reader_skew_route_open_incomplete_target_is_unmarked() {
4667 let mut body = reply();
4668 body["target"] = target();
4669 assert!(RouteOpenReplyExt::read_from(&body)
4670 .unwrap()
4671 .target
4672 .is_some());
4673 for key in [
4674 "incarnation",
4675 "kind",
4676 "spawn",
4677 "authority_epoch",
4678 "first_party",
4679 "approved_declarations_digest",
4680 ] {
4681 let mut incomplete = body.clone();
4682 incomplete["target"].as_object_mut().unwrap().remove(key);
4683 assert_eq!(
4684 RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4685 None,
4686 "{key}"
4687 );
4688 }
4689 body["target"] = Value::Null;
4690 assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4691 }
4692
4693 #[test]
4694 fn reader_skew_route_open_effective_digest_is_optional() {
4695 let mut body = reply();
4696 body["target"] = target();
4697 let legacy = RouteOpenReplyExt::read_from(&body).unwrap();
4698 assert_eq!(
4699 legacy
4700 .target
4701 .as_ref()
4702 .unwrap()
4703 .effective_declarations_digest,
4704 None
4705 );
4706 let mut encoded = reply();
4707 RouteOpenReplyExt::new()
4708 .with_target(Some(
4709 legacy
4710 .target
4711 .clone()
4712 .unwrap()
4713 .with_effective_declarations_digest(Some("effective".into())),
4714 ))
4715 .write_to(&mut encoded)
4716 .unwrap();
4717 body["target"]["effective_declarations_digest"] = json!("effective");
4718 assert_eq!(encoded, body);
4719 let decoded = RouteOpenReplyExt::read_from(&body).unwrap().target.unwrap();
4720 assert_eq!(
4721 decoded.effective_declarations_digest.as_deref(),
4722 Some("effective")
4723 );
4724 assert_eq!(
4725 decoded.approved_declarations_digest.as_deref(),
4726 Some("approved")
4727 );
4728 body["target"]["effective_declarations_digest"] = json!(42);
4729 assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap(), legacy);
4730 }
4731
4732 #[test]
4733 fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4734 for (kind, expected) in [
4735 ("prefix", RouteOpenTargetKind::Prefix),
4736 ("unsupervised", RouteOpenTargetKind::Unsupervised),
4737 ] {
4738 let mut body = reply();
4739 body["target"] = target();
4740 body["target"]["kind"] = json!(kind);
4741 body["target"]["spawn"] = json!("not-a-spawn");
4743 body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4744 body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4745 body["target"]["effective_declarations_digest"] = json!("effective");
4746 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4747 let target = ext.target.as_ref().unwrap();
4748 assert_eq!(target.kind, expected);
4749 assert_eq!(target.spawn, None);
4750 assert_eq!(target.authority_epoch, None);
4751 assert_eq!(target.approved_declarations_digest, None);
4752 assert_eq!(target.effective_declarations_digest, None);
4753 assert!(!target.first_party);
4754 let mut encoded = reply();
4755 ext.write_to(&mut encoded).unwrap();
4756 for key in [
4757 "spawn",
4758 "authority_epoch",
4759 "approved_declarations_digest",
4760 "effective_declarations_digest",
4761 ] {
4762 assert!(encoded["target"].get(key).is_none());
4763 }
4764 }
4765 }
4766
4767 #[test]
4768 fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4769 let mut body = reply();
4770 body["target"] = target();
4771 body["target"]["kind"] = json!("future-kind");
4772 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4773 let target = ext.target.unwrap();
4774 assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4775 assert_eq!(target.spawn, None);
4776 assert_eq!(target.authority_epoch, None);
4777 assert_eq!(target.approved_declarations_digest, None);
4778 assert!(!target.first_party);
4779 }
4780
4781 #[test]
4782 fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4783 for field in ["spawn", "authority_epoch"] {
4784 let mut body = reply();
4785 body["target"] = target();
4786 body["target"][field] = json!(9_007_199_254_740_991_u64);
4787 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4788 assert_eq!(
4789 serde_json::to_value(ext).unwrap()["target"][field],
4790 9_007_199_254_740_991_u64
4791 );
4792 for invalid in [
4793 json!(9_007_199_254_740_992_u64),
4794 json!(-1),
4795 json!(1.5),
4796 json!("17"),
4797 ] {
4798 body["target"][field] = invalid;
4799 assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4800 let mut incomplete = body.clone();
4801 incomplete["target"]
4802 .as_object_mut()
4803 .unwrap()
4804 .remove("incarnation");
4805 assert!(
4806 RouteOpenReplyExt::read_from(&incomplete).is_err(),
4807 "{field}"
4808 );
4809 }
4810 }
4811 }
4812
4813 #[test]
4814 fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4815 let mut body = request();
4816 let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4817 assert_eq!(
4818 RouteOpenRequestExt::read_from(&body).unwrap(),
4819 RouteOpenRequestExt::new()
4820 );
4821 RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4822 assert_eq!(body, request());
4823 body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4824 let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4825 assert_eq!(
4826 decoded.accepts_close_reasons,
4827 Some(vec!["authority_changed".into(), "future-reason".into()])
4828 );
4829 let mut encoded = request();
4830 RouteOpenRequestExt::new()
4831 .with_accepts_close_reasons(decoded.accepts_close_reasons)
4832 .write_to(&mut encoded)
4833 .unwrap();
4834 assert_eq!(encoded, body);
4835 assert_eq!(
4836 serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4837 legacy
4838 );
4839 RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4840 assert_eq!(encoded, request());
4841 assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4842 }
4843
4844 #[test]
4845 fn reader_skew_route_open_helpers_refuse_other_bodies() {
4846 for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4847 assert!(RouteOpenRequestExt::read_from(&body).is_err());
4848 assert!(RouteOpenReplyExt::read_from(&body).is_err());
4849 assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4850 assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4851 }
4852 }
4853
4854 #[test]
4855 fn reader_skew_route_open_target_constructor_validates_like_reader() {
4856 let spawn = RouteOpenTarget::new(
4857 "daemon",
4858 RouteOpenTargetKind::Spawn,
4859 Some(17),
4860 Some(23),
4861 true,
4862 Some("approved".into()),
4863 )
4864 .unwrap();
4865 assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4866 for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4867 assert!(RouteOpenTarget::new(
4868 "daemon",
4869 RouteOpenTargetKind::Spawn,
4870 Some(spawn),
4871 Some(epoch),
4872 true,
4873 Some("approved".into())
4874 )
4875 .is_err());
4876 }
4877 }
4878}
4879
4880#[cfg(test)]
4881mod claim_wire_tests {
4882 use super::*;
4883 use serde_json::{json, Value};
4884
4885 fn legacy_provenance() -> SupervisorModuleProvenance {
4886 SupervisorModuleProvenance {
4887 module_id: "worker".into(),
4888 module_declared: ModuleDeclaredProvenance::Unverifiable,
4889 daemon_observed: SupervisorObservedProcess {
4890 launch_nonce_source: None,
4891 pid: None,
4892 spawned_at_ms: None,
4893 spawned_from: None,
4894 running_image: RunningImageAgreement::Unavailable {
4895 reason: RunningImageUnavailableReason::NotRunning,
4896 },
4897 },
4898 }
4899 }
4900
4901 #[test]
4902 fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4903 let legacy = legacy_provenance();
4904 let original = serde_json::to_value(&legacy).unwrap();
4905 let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4906 assert_eq!(absent.registration, None);
4907 let mut wire = original.clone();
4908 absent.write_to(&mut wire).unwrap();
4909 assert_eq!(wire, original);
4910 for (method, spelling) in [
4911 (RegistrationMethod::Channel, "channel"),
4912 (RegistrationMethod::Nonce, "nonce"),
4913 ] {
4914 let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4915 ext.write_to(&mut wire).unwrap();
4916 assert_eq!(wire["registration"], spelling);
4917 assert_eq!(
4918 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4919 ext
4920 );
4921 let old_reader: SupervisorModuleProvenance =
4922 serde_json::from_value(wire.clone()).unwrap();
4923 assert_eq!(old_reader, legacy);
4924 assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4925 }
4926 absent.write_to(&mut wire).unwrap();
4927 assert_eq!(wire, original);
4928 for mut invalid in [Value::Null, json!([]), json!("entry")] {
4929 assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4930 assert!(absent.write_to(&mut invalid).is_err());
4931 }
4932 }
4933
4934 #[test]
4935 fn provenance_waiting_previous_detail_preserves_legacy_entry() {
4936 let legacy = legacy_provenance();
4937 let mut wire = serde_json::to_value(&legacy).unwrap();
4938 let absent = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4939 assert_eq!(absent.waiting_for_previous_detail, None);
4940 let detail = "waiting: container survivors (pids [42])";
4941 let ext = absent
4942 .clone()
4943 .with_waiting_for_previous_detail(Some(detail.into()));
4944 ext.write_to(&mut wire).unwrap();
4945 assert_eq!(wire["waiting_for_previous_detail"], detail);
4946 assert_eq!(
4947 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4948 ext
4949 );
4950 assert_eq!(
4951 serde_json::from_value::<SupervisorModuleProvenance>(wire.clone()).unwrap(),
4952 legacy
4953 );
4954 absent.write_to(&mut wire).unwrap();
4955 assert!(wire.get("waiting_for_previous_detail").is_none());
4956 }
4957
4958 #[test]
4959 fn provenance_unknown_registration_is_not_channel_or_nonce() {
4960 let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4961 wire["registration"] = json!("future_method");
4962 let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4963 assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4964 assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4965 assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4966 wire["registration"] = json!(false);
4967 assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4968 }
4969
4970 #[test]
4971 fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4972 let original = serde_json::to_value(legacy_provenance()).unwrap();
4973 for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4974 let mut golden = original.clone();
4975 golden["registration_declaration"] = json!(declaration);
4976 let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4977 assert_eq!(
4978 serde_json::to_value(&extension).unwrap(),
4979 json!({
4980 "registration_declaration": declaration
4981 })
4982 );
4983 let mut written = original.clone();
4984 extension.write_to(&mut written).unwrap();
4985 assert_eq!(written, golden);
4986 assert_eq!(
4987 serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4988 legacy_provenance()
4989 );
4990 SupervisorModuleProvenanceExt::new()
4991 .write_to(&mut written)
4992 .unwrap();
4993 assert_eq!(written, original);
4994 }
4995 }
4996
4997 #[test]
4998 fn admission_refusal_is_optional_and_open() {
4999 let entry = SupervisorEntry::new(
5000 "worker",
5001 "stopped",
5002 true,
5003 false,
5004 SupervisorHealthStatus::Unknown,
5005 );
5006 let original = serde_json::to_value(&entry).unwrap();
5007 assert!(original.get("admission_refused").is_none());
5008 let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
5009 assert_eq!(read.admission_refused, None);
5010 assert_eq!(serde_json::to_value(read).unwrap(), original);
5011 assert_eq!(
5012 REGISTRATION_CHANNEL_UNSUPPORTED,
5013 "registration_channel_unsupported"
5014 );
5015 for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
5016 let mut wire = original.clone();
5017 wire["admission_refused"] = json!(reason);
5018 let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
5019 assert_eq!(read.admission_refused.as_deref(), Some(reason));
5020 assert_eq!(serde_json::to_value(read).unwrap(), wire);
5021 let built = entry.clone().with_admission_refused(Some(reason.into()));
5022 assert_eq!(serde_json::to_value(built).unwrap(), wire);
5023 }
5024 }
5025}