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