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