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
88mod rescan_checked;
89pub use rescan_checked::*;
90
91mod app_open;
92pub use app_open::*;
93
94mod connection_describe;
95pub use connection_describe::*;
96
97mod scope_watch;
98pub use scope_watch::*;
99
100mod subtree;
101pub use subtree::*;
102mod tree;
103pub use tree::*;
104
105#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
107pub struct ConsumerIdentity {
108 pub module_id: String,
109 pub launch_nonce: String,
110}
111
112impl std::fmt::Debug for ConsumerIdentity {
117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118 f.debug_struct("ConsumerIdentity")
119 .field("module_id", &self.module_id)
120 .field(
121 "launch_nonce",
122 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
123 )
124 .finish()
125 }
126}
127
128pub mod config;
139
140pub mod ops {
141 pub const SERVER: &str = "server.";
142 pub const CATALOG: &str = "catalog.";
143 pub const ROUTE: &str = "route.";
144 pub const SUPERVISOR: &str = "supervisor.";
145 pub const CONFIG: &str = "config.";
146
147 pub const SERVER_DESCRIBE: &str = "server.describe";
148 pub const DAEMON_SHUTDOWN_INTENT: &str = "daemon.shutdown_intent";
149 pub const CATALOG_LIST: &str = "catalog.list";
150 pub const CATALOG_WATCH: &str = "catalog.watch";
151 pub const SCOPE_WATCH: &str = "scope.watch";
152 pub const ROUTE_OPEN: &str = "route.open";
153 pub const ROUTE_POLL: &str = "route.poll";
154 pub const ROUTE_CLOSING: &str = "route.closing";
155 pub const ROUTE_CLOSED: &str = "route.closed";
156 pub const SUPERVISOR_LIST: &str = "supervisor.list";
157 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
158 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
159 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
160 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
161 pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
162 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
163 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
164 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
165 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
166 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
167 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
168 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
169 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
170 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
171 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
172 pub const ACTIVITY_RECORD: &str = "activity.record";
173 pub const ACTIVITY_QUERY: &str = "activity.query";
174 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
175 pub const APP_OPEN: &str = "app.open";
176 pub const CONNECTION_DESCRIBE: &str = "connection.describe";
177}
178
179#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
181#[serde(tag = "op")]
182#[allow(clippy::large_enum_variant)]
185pub enum ClientControlRequest {
186 #[serde(rename = "daemon.shutdown_intent")]
189 DaemonShutdownIntent {
190 #[serde(default)]
191 intent: serde_json::Value,
192 },
193 #[serde(rename = "server.describe")]
194 ServerDescribe {},
195 #[serde(rename = "catalog.list")]
196 CatalogList {
197 #[serde(default)]
202 module_id: Option<String>,
203 },
204 #[serde(rename = "route.open")]
205 RouteOpen {
206 target: RouteTarget,
207 identity: BindIdentity,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
217 consumer_identity: Option<ConsumerIdentity>,
218 #[serde(default, skip_serializing_if = "Option::is_none")]
226 consumer_capabilities: Option<Vec<String>>,
227 #[serde(default, skip_serializing_if = "Option::is_none")]
238 role_versions: Option<BTreeMap<String, String>>,
239 #[serde(default, skip_serializing_if = "Option::is_none")]
243 busy_refusals: Option<bool>,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
246 admission_facts: Option<serde_json::Value>,
247 #[serde(default, skip_serializing_if = "Option::is_none")]
254 scope: Option<ScopeSelector>,
255 },
256 #[serde(rename = "route.poll")]
257 RoutePoll {
258 route_channel: u16,
259 route_epoch: u32,
260 kind: PollKind,
261 },
262 #[serde(rename = "supervisor.list")]
263 SupervisorList {},
264 #[serde(rename = "supervisor.spawn_snapshot")]
266 SupervisorSpawnSnapshot {},
267 #[serde(rename = "supervisor.spawn_subscribe")]
283 SupervisorSpawnSubscribe {
284 #[serde(default, skip_serializing_if = "Option::is_none")]
285 since: Option<SpawnCursor>,
286 },
287 #[serde(rename = "supervisor.restart")]
288 SupervisorRestart {
289 module_id: String,
290 #[serde(default, skip_serializing_if = "Option::is_none")]
300 drain_timeout_ms: Option<u64>,
301 },
302 #[serde(rename = "supervisor.swap")]
317 SupervisorSwap {
318 module_id: String,
319 #[serde(default, skip_serializing_if = "Option::is_none")]
322 ready_timeout_ms: Option<u64>,
323 },
324 #[serde(rename = "supervisor.reload")]
325 SupervisorReload { module_id: String },
326 #[serde(rename = "supervisor.rescan")]
327 SupervisorRescan {
328 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
348 preview: bool,
349 },
350 #[serde(rename = "supervisor.rescan_checked")]
374 SupervisorRescanChecked {
375 preview: bool,
376 #[serde(default, skip_serializing_if = "Option::is_none")]
377 candidate: Option<String>,
378 #[serde(default, skip_serializing_if = "Option::is_none")]
379 expect: Option<RescanExpect>,
380 },
381 #[serde(rename = "supervisor.release_reserved")]
385 SupervisorReleaseReserved { module_id: String },
386 #[serde(rename = "supervisor.set_enabled")]
387 SupervisorSetEnabled { module_id: String, enabled: bool },
388 #[serde(rename = "supervisor.health_probe")]
389 SupervisorHealthProbe { module_id: String },
390 #[serde(rename = "supervisor.health")]
391 SupervisorHealth {},
392 #[serde(rename = "supervisor.routes")]
405 SupervisorRoutes {
406 #[serde(default, skip_serializing_if = "Option::is_none")]
407 module_id: Option<String>,
408 },
409 #[serde(rename = "supervisor.provenance")]
412 SupervisorProvenance {
413 #[serde(default, skip_serializing_if = "Option::is_none")]
414 module_id: Option<String>,
415 },
416 #[serde(rename = "supervisor.stderr_tail")]
424 SupervisorStderrTail {
425 module_id: String,
426 #[serde(default, skip_serializing_if = "Option::is_none")]
427 max_lines: Option<u32>,
428 #[serde(default, skip_serializing_if = "Option::is_none")]
429 max_bytes: Option<u32>,
430 },
431 #[serde(rename = "supervisor.terminals")]
444 SupervisorTerminals { module_id: String },
445}
446
447#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
449#[serde(tag = "op")]
450pub enum ClientControlResponse {
451 #[serde(rename = "daemon.shutdown_intent")]
452 DaemonShutdownIntent { intent: String, expires_at_ms: u64 },
453 #[serde(rename = "server.describe")]
454 ServerDescribe {
455 protocol_ver: u8,
456 subc_ops: Vec<String>,
457 capabilities: Vec<String>,
458 connected_clients: u64,
459 #[serde(default, skip_serializing_if = "Option::is_none")]
460 counters: Option<serde_json::Value>,
461 #[serde(default, skip_serializing_if = "Option::is_none")]
468 build_git_sha: Option<String>,
469 #[serde(default, skip_serializing_if = "Option::is_none")]
475 build_lock_digest: Option<String>,
476 #[serde(default, skip_serializing_if = "Vec::is_empty")]
480 capability_requirements: Vec<CapabilityRequirementStatus>,
481 #[serde(default, skip_serializing_if = "Option::is_none")]
486 machine_id: Option<String>,
487 #[serde(default, skip_serializing_if = "Option::is_none")]
496 config_path: Option<PathBuf>,
497 },
498 #[serde(rename = "catalog.list")]
499 CatalogList {
500 generation: u64,
501 modules: Vec<CatalogEntry>,
502 subc_ops: Vec<String>,
503 },
504 #[serde(rename = "route.open")]
505 RouteOpen {
506 route_channel: u16,
507 route_epoch: u32,
508 #[serde(default, skip_serializing_if = "Option::is_none")]
510 request_window: Option<usize>,
511 #[serde(default, skip_serializing_if = "Option::is_none")]
513 watch_window: Option<usize>,
514 },
515 #[serde(rename = "route.poll")]
516 RoutePoll {
517 route_channel: u16,
518 route_epoch: u32,
519 status: Option<String>,
520 live: Option<bool>,
521 },
522 #[serde(rename = "supervisor.list")]
523 SupervisorList {
524 generation: u64,
525 modules: Vec<SupervisorEntry>,
526 #[serde(default, skip_serializing_if = "Option::is_none")]
527 daemon: Option<DaemonResources>,
528 #[serde(default, skip_serializing_if = "Option::is_none")]
529 agent_commands: Option<Vec<AgentCommandResources>>,
530 },
531 #[serde(rename = "supervisor.spawn_snapshot")]
532 SupervisorSpawnSnapshot {
533 #[serde(flatten)]
534 snapshot: SpawnSnapshot,
535 },
536 #[serde(rename = "supervisor.ack")]
537 SupervisorAck { module_id: String, applied: bool },
538 #[serde(rename = "supervisor.rescan")]
539 SupervisorRescan {
540 #[serde(flatten)]
541 result: SupervisorRescanResult,
542 },
543 #[serde(rename = "supervisor.health_probe")]
544 SupervisorHealthProbe {
545 module_id: String,
546 status: HealthStatus,
547 #[serde(default, skip_serializing_if = "Option::is_none")]
548 detail: Option<String>,
549 #[serde(default, skip_serializing_if = "Option::is_none")]
550 metrics: Option<serde_json::Value>,
551 },
552 #[serde(rename = "supervisor.health")]
553 SupervisorHealth {
554 generation: u64,
555 modules: Vec<SupervisorHealthEntry>,
556 },
557 #[serde(rename = "supervisor.routes")]
558 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
559 #[serde(rename = "supervisor.provenance")]
560 SupervisorProvenance {
561 daemon: SupervisorDaemonProvenance,
562 modules: Vec<SupervisorModuleProvenance>,
563 },
564 #[serde(rename = "supervisor.stderr_tail")]
565 SupervisorStderrTail {
566 module_id: String,
567 #[serde(flatten)]
568 tail: StderrTail,
569 },
570 #[serde(rename = "supervisor.terminals")]
571 SupervisorTerminals {
572 module_id: String,
573 #[serde(flatten)]
574 terminals: TerminalHistory,
575 },
576}
577
578pub const ROUTE_CLOSE_REASONS_CAPABILITY: &str = "route-close-reasons/v1";
580
581#[non_exhaustive]
585#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
586pub struct RouteOpenRequestExt {
587 #[serde(default, skip_serializing_if = "Option::is_none")]
588 pub accepts_close_reasons: Option<Vec<String>>,
589}
590
591impl RouteOpenRequestExt {
592 pub fn new() -> Self {
593 Self::default()
594 }
595
596 #[must_use]
597 pub fn with_accepts_close_reasons(mut self, reasons: Option<Vec<String>>) -> Self {
598 self.accepts_close_reasons = reasons;
599 self
600 }
601
602 pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
604 require_route_open_object(body)?;
605 serde_json::from_value(body.clone())
606 }
607
608 pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
611 write_route_open_ext(body, self, &["accepts_close_reasons"])
612 }
613}
614
615#[non_exhaustive]
618#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
619pub struct RouteOpenReplyExt {
620 #[serde(
622 default,
623 skip_serializing_if = "Option::is_none",
624 deserialize_with = "deserialize_route_open_target"
625 )]
626 pub target: Option<RouteOpenTarget>,
627}
628
629impl RouteOpenReplyExt {
630 pub fn new() -> Self {
631 Self::default()
632 }
633
634 #[must_use]
635 pub fn with_target(mut self, target: Option<RouteOpenTarget>) -> Self {
636 self.target = target;
637 self
638 }
639
640 pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
642 require_route_open_object(body)?;
643 serde_json::from_value(body.clone())
644 }
645
646 pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
649 write_route_open_ext(body, self, &["target"])
650 }
651}
652
653fn require_route_open_object(body: &serde_json::Value) -> serde_json::Result<()> {
654 if body.is_object()
655 && body.get("op").and_then(serde_json::Value::as_str) == Some(ops::ROUTE_OPEN)
656 {
657 Ok(())
658 } else {
659 Err(serde_json::Error::custom(
660 "expected a route.open body object",
661 ))
662 }
663}
664
665fn write_route_open_ext(
666 body: &mut serde_json::Value,
667 ext: &impl Serialize,
668 keys: &[&str],
669) -> serde_json::Result<()> {
670 require_route_open_object(body)?;
671 let serde_json::Value::Object(fields) = serde_json::to_value(ext)? else {
672 unreachable!("route.open companions serialize as objects");
673 };
674 let object = body.as_object_mut().expect("validated route.open object");
675 for key in keys {
676 object.remove(*key);
677 }
678 object.extend(fields);
679 Ok(())
680}
681
682#[non_exhaustive]
684#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
685#[serde(rename_all = "snake_case")]
686pub enum RouteOpenTargetKind {
687 Spawn,
688 Prefix,
689 Unsupervised,
690 #[serde(other)]
691 Unknown,
692}
693
694#[non_exhaustive]
697#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
698pub struct RouteOpenTarget {
699 pub incarnation: String,
700 pub kind: RouteOpenTargetKind,
701 #[serde(skip_serializing_if = "Option::is_none")]
702 pub spawn: Option<u64>,
703 #[serde(skip_serializing_if = "Option::is_none")]
704 pub authority_epoch: Option<u64>,
705 pub first_party: bool,
706 #[serde(skip_serializing_if = "Option::is_none")]
707 pub approved_declarations_digest: Option<String>,
708}
709
710impl RouteOpenTarget {
711 pub fn new(
714 incarnation: impl Into<String>,
715 kind: RouteOpenTargetKind,
716 spawn: Option<u64>,
717 authority_epoch: Option<u64>,
718 first_party: bool,
719 approved_declarations_digest: Option<String>,
720 ) -> serde_json::Result<Self> {
721 serde_json::from_value(serde_json::json!({
722 "incarnation": incarnation.into(), "kind": kind,
723 "spawn": spawn, "authority_epoch": authority_epoch,
724 "first_party": first_party,
725 "approved_declarations_digest": approved_declarations_digest,
726 }))
727 }
728}
729
730impl<'de> Deserialize<'de> for RouteOpenTarget {
731 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
732 decode_route_open_target(serde_json::Value::deserialize(decoder)?)
733 .map_err(D::Error::custom)?
734 .ok_or_else(|| D::Error::custom("incomplete route.open target"))
735 }
736}
737
738fn deserialize_route_open_target<'de, D: Deserializer<'de>>(
739 decoder: D,
740) -> Result<Option<RouteOpenTarget>, D::Error> {
741 decode_route_open_target(serde_json::Value::deserialize(decoder)?).map_err(D::Error::custom)
742}
743
744fn decode_route_open_target(
745 mut value: serde_json::Value,
746) -> serde_json::Result<Option<RouteOpenTarget>> {
747 if value.is_null() {
748 return Ok(None);
749 }
750 let object = value
751 .as_object_mut()
752 .ok_or_else(|| serde_json::Error::custom("expected target object"))?;
753 let is_spawn = object.get("kind").and_then(serde_json::Value::as_str) == Some("spawn");
754 if is_spawn {
755 for field in ["spawn", "authority_epoch"] {
757 if let Some(integer) = object.get(field) {
758 deserialize_optional_attestation_integer(integer)?;
759 }
760 }
761 } else {
762 for field in ["spawn", "authority_epoch", "approved_declarations_digest"] {
763 object.remove(field);
764 }
765 }
766 if ["incarnation", "kind", "first_party"]
767 .iter()
768 .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null))
769 || (is_spawn
770 && ["spawn", "authority_epoch", "approved_declarations_digest"]
771 .iter()
772 .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null)))
773 {
774 return Ok(None);
775 }
776 #[derive(Deserialize)]
777 struct Wire {
778 incarnation: String,
779 kind: RouteOpenTargetKind,
780 spawn: Option<u64>,
781 authority_epoch: Option<u64>,
782 first_party: bool,
783 approved_declarations_digest: Option<String>,
784 }
785 let wire: Wire = serde_json::from_value(value)?;
786 Ok(Some(RouteOpenTarget {
787 incarnation: wire.incarnation,
788 kind: wire.kind,
789 spawn: wire.spawn,
790 authority_epoch: wire.authority_epoch,
791 first_party: is_spawn && wire.first_party,
792 approved_declarations_digest: wire.approved_declarations_digest,
793 }))
794}
795
796fn deserialize_optional_attestation_integer<'de, D: Deserializer<'de>>(
797 decoder: D,
798) -> Result<Option<u64>, D::Error> {
799 let value = Option::<u64>::deserialize(decoder)?;
800 if value.is_some_and(|integer| integer > MAX_ATTESTATION_INTEGER) {
801 return Err(D::Error::custom("attestation integer exceeds 2^53-1"));
802 }
803 Ok(value)
804}
805
806#[non_exhaustive]
809#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
810#[serde(tag = "op", rename = "catalog.watch")]
811pub struct CatalogWatchRequest {}
812
813impl CatalogWatchRequest {
814 pub const OP: &'static str = ops::CATALOG_WATCH;
815
816 pub fn new() -> Self {
817 Self {}
818 }
819}
820
821#[non_exhaustive]
825#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
826#[serde(tag = "op", rename = "catalog.watch")]
827pub struct CatalogWatchResponse {
828 pub generation: u64,
829}
830
831impl CatalogWatchResponse {
832 pub const OP: &'static str = ops::CATALOG_WATCH;
833
834 pub fn new(generation: u64) -> Self {
835 Self { generation }
836 }
837}
838
839impl<'de> Deserialize<'de> for CatalogWatchRequest {
840 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
841 #[derive(Deserialize)]
842 #[serde(tag = "op")]
843 enum Wire {
844 #[serde(rename = "catalog.watch")]
845 Body {},
846 }
847 let Wire::Body {} = Wire::deserialize(decoder)?;
848 Ok(Self::new())
849 }
850}
851
852impl<'de> Deserialize<'de> for CatalogWatchResponse {
853 fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
854 #[derive(Deserialize)]
855 #[serde(tag = "op")]
856 enum Wire {
857 #[serde(rename = "catalog.watch")]
858 Body { generation: u64 },
859 }
860 let Wire::Body { generation } = Wire::deserialize(decoder)?;
861 Ok(Self::new(generation))
862 }
863}
864
865#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
870#[serde(tag = "op")]
871pub enum ClientControlPush {
872 #[serde(rename = "route.closing")]
873 RouteClosing {
874 module_id: String,
875 #[serde(default)]
878 channels: Vec<u16>,
879 reason: RouteCloseReason,
880 },
881 #[serde(rename = "route.closed")]
882 RouteClosed {
883 module_id: String,
884 #[serde(default)]
887 channels: Vec<u16>,
888 reason: RouteCloseReason,
889 drained: bool,
891 abandoned: u32,
894 #[serde(default)]
896 excluded_subscriptions: u32,
897 #[serde(default, skip_serializing_if = "Option::is_none")]
903 terminal: Option<bool>,
904 },
905}
906
907#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
909pub struct SpawnCursor {
910 pub daemon_incarnation: String,
911 pub seq: u64,
912}
913
914#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
916pub struct LiveSpawn {
917 pub module_id: String,
918 pub spawn_generation: u64,
924 pub pid: u32,
925 pub spawned_at_ms: u64,
926}
927
928#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
930pub struct SpawnSnapshot {
931 pub cursor: SpawnCursor,
932 pub ring_bound: u64,
934 pub live: Vec<LiveSpawn>,
935}
936
937#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
939#[serde(rename_all = "snake_case")]
940pub enum SpawnEventKind {
941 Spawned,
942 Exited,
943}
944
945#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
951pub struct SpawnEvent {
952 pub cursor: SpawnCursor,
953 pub kind: SpawnEventKind,
954 pub module_id: String,
955 pub spawn_generation: u64,
957 pub pid: u32,
958 #[serde(default, skip_serializing_if = "Option::is_none")]
959 pub exit_code: Option<i32>,
960 #[serde(default, skip_serializing_if = "Option::is_none")]
961 pub exit_signal: Option<i32>,
962}
963
964#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
966pub struct StderrTail {
967 pub capture: StderrCaptureState,
968 pub entries: Vec<StderrTailEntry>,
969 #[serde(default, skip_serializing_if = "is_zero_u64")]
978 pub dropped_lines: u64,
979}
980
981#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
983pub struct SupervisorRouteModule {
984 pub module_id: String,
985 pub routes: Vec<SupervisorRoute>,
986}
987
988#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
990pub struct SupervisorRoute {
991 pub consumer: SupervisorRouteConsumer,
992 pub age_ms: u64,
994 pub draining: bool,
997 #[serde(default, skip_serializing_if = "Option::is_none")]
1003 pub drain_reason: Option<RouteCloseReason>,
1004}
1005
1006#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1008pub struct SupervisorModuleProvenance {
1009 pub module_id: String,
1010 pub module_declared: ModuleDeclaredProvenance,
1011 pub daemon_observed: SupervisorObservedProcess,
1012}
1013
1014#[non_exhaustive]
1017#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1018pub struct SupervisorModuleProvenanceExt {
1019 #[serde(default, skip_serializing_if = "Option::is_none")]
1021 pub registration: Option<RegistrationMethod>,
1022 #[serde(default, skip_serializing_if = "Option::is_none")]
1026 pub registration_declaration: Option<String>,
1027}
1028
1029impl SupervisorModuleProvenanceExt {
1030 pub fn new() -> Self {
1031 Self::default()
1032 }
1033
1034 #[must_use]
1035 pub fn with_registration(mut self, registration: Option<RegistrationMethod>) -> Self {
1036 self.registration = registration;
1037 self
1038 }
1039
1040 pub fn read_from(entry: &serde_json::Value) -> serde_json::Result<Self> {
1042 if !entry.is_object() {
1043 return Err(serde_json::Error::custom(
1044 "expected a module provenance entry object",
1045 ));
1046 }
1047 serde_json::from_value(entry.clone())
1048 }
1049
1050 pub fn write_to(&self, entry: &mut serde_json::Value) -> serde_json::Result<()> {
1053 let object = entry.as_object_mut().ok_or_else(|| {
1054 serde_json::Error::custom("expected a module provenance entry object")
1055 })?;
1056 object.remove("registration");
1057 if let Some(method) = &self.registration {
1058 object.insert("registration".into(), serde_json::to_value(method)?);
1059 }
1060 object.remove("registration_declaration");
1061 if let Some(declaration) = &self.registration_declaration {
1062 object.insert(
1063 "registration_declaration".into(),
1064 declaration.clone().into(),
1065 );
1066 }
1067 Ok(())
1068 }
1069}
1070
1071#[non_exhaustive]
1074#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1075#[serde(rename_all = "snake_case")]
1076pub enum RegistrationMethod {
1077 Channel,
1078 Nonce,
1079 #[serde(other)]
1080 Unknown,
1081}
1082
1083pub const REGISTRATION_CHANNEL_UNSUPPORTED: &str = "registration_channel_unsupported";
1086
1087#[derive(Debug, Clone, PartialEq)]
1089pub enum ModuleDeclaredProvenance {
1090 Reported {
1091 build: ManifestProvenance,
1092 },
1093 Unverifiable,
1094 Unknown {
1097 tag: String,
1098 body: OrderedJsonObject,
1099 },
1100}
1101
1102#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1107pub struct SupervisorObservedProcess {
1108 #[serde(default, skip_serializing_if = "Option::is_none")]
1114 pub launch_nonce_source: Option<String>,
1115 #[serde(default, skip_serializing_if = "Option::is_none")]
1116 pub pid: Option<u32>,
1117 #[serde(default, skip_serializing_if = "Option::is_none")]
1118 pub spawned_at_ms: Option<u64>,
1119 #[serde(default, skip_serializing_if = "Option::is_none")]
1120 pub spawned_from: Option<PathBuf>,
1121 pub running_image: RunningImageAgreement,
1122}
1123
1124#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1141#[non_exhaustive]
1142pub struct PendingReloadVerdict {
1143 pub path: ReloadPathAgreement,
1144 pub image: RunningImageAgreement,
1145 #[serde(default, skip_serializing_if = "Option::is_none")]
1146 pub spec: Option<LaunchSpecAgreement>,
1147}
1148
1149impl PendingReloadVerdict {
1150 #[must_use]
1152 pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
1153 Self {
1154 path,
1155 image,
1156 spec: None,
1157 }
1158 }
1159
1160 #[must_use]
1162 pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
1163 self.spec = spec;
1164 self
1165 }
1166}
1167
1168#[cfg(test)]
1169mod launch_spec_wire_tests {
1170 use super::*;
1171
1172 #[test]
1173 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
1174 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
1175 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
1176 assert_eq!(parsed.spec, None);
1177 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
1178 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
1179 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
1180 assert!(
1181 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
1182 );
1183 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
1184 let unavailable = LaunchSpecAgreement::Unavailable {
1185 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
1186 };
1187 let encoded = serde_json::to_string(&unavailable).unwrap();
1188 assert_eq!(
1189 encoded,
1190 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
1191 );
1192 assert_eq!(
1193 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
1194 unavailable
1195 );
1196 }
1197}
1198
1199#[derive(Debug, Clone, PartialEq)]
1202pub enum LaunchSpecAgreement {
1203 Match,
1204 Mismatch,
1205 Unavailable {
1206 reason: LaunchSpecUnavailableReason,
1207 },
1208 Unknown {
1209 tag: String,
1210 body: OrderedJsonObject,
1211 },
1212}
1213
1214open_string_enum! {
1215 LaunchSpecUnavailableReason {
1216 NotRunning => "not_running",
1217 SpawnedSpecUnavailable => "spawned_spec_unavailable",
1218 }
1219}
1220
1221#[derive(Debug, Clone, PartialEq)]
1223pub enum ReloadPathAgreement {
1224 Match,
1225 Mismatch {
1226 configured: PathBuf,
1227 spawned_from: PathBuf,
1228 },
1229 Unavailable {
1230 reason: ReloadPathUnavailableReason,
1231 },
1232 Unknown {
1233 tag: String,
1234 body: OrderedJsonObject,
1235 },
1236}
1237
1238open_string_enum! {
1239 ReloadPathUnavailableReason {
1241 NotRunning => "not_running",
1242 SpawnedPathUnavailable => "spawned_path_unavailable",
1243 }
1244}
1245
1246#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1248pub struct SupervisorDaemonProvenance {
1249 pub daemon_build: DaemonBuildProvenance,
1250 pub daemon_observed: DaemonObservedProcess,
1251}
1252
1253#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1255pub struct DaemonBuildProvenance {
1256 #[serde(default, skip_serializing_if = "Option::is_none")]
1257 pub build_git_sha: Option<String>,
1258 #[serde(default, skip_serializing_if = "Option::is_none")]
1259 pub build_lock_digest: Option<String>,
1260}
1261
1262#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1264pub struct DaemonObservedProcess {
1265 #[serde(default, skip_serializing_if = "Option::is_none")]
1266 pub pid: Option<u32>,
1267 #[serde(default, skip_serializing_if = "Option::is_none")]
1272 pub started_at_ms: Option<u64>,
1273 pub running_image: RunningImageAgreement,
1274}
1275
1276#[derive(Debug, Clone, PartialEq)]
1278pub enum RunningImageAgreement {
1279 Match {
1280 evidence: RunningImageEvidence,
1281 },
1282 Mismatch {
1283 running: RunningImageEvidence,
1284 disk: RunningImageEvidence,
1285 },
1286 Unavailable {
1287 reason: RunningImageUnavailableReason,
1288 },
1289 Unknown {
1292 tag: String,
1293 body: OrderedJsonObject,
1294 },
1295}
1296
1297#[derive(Debug, Clone, PartialEq)]
1299pub enum RunningImageEvidence {
1300 LinuxProcSha256 {
1301 digest: String,
1302 },
1303 MacosSpawnInode {
1304 device: u64,
1305 inode: u64,
1306 },
1307 WindowsSpawnFileId {
1309 volume_serial_number: u64,
1310 file_id: [u8; 16],
1311 },
1312 Unknown {
1315 tag: String,
1316 body: OrderedJsonObject,
1317 },
1318}
1319
1320open_string_enum! {
1321 RunningImageUnavailableReason {
1323 NotRunning => "not_running",
1324 NotYetMeasured => "not_yet_measured",
1325 UnsupportedPlatform => "unsupported_platform",
1326 RunningExecutableUnreadable => "running_executable_unreadable",
1327 RunningExecutablePermissionDenied => "running_executable_permission_denied",
1328 ProcessHidden => "process_hidden",
1329 SpawnedPathUnreadable => "spawned_path_unreadable",
1330 HashFailed => "hash_failed",
1331 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
1332 }
1333}
1334
1335#[derive(Debug, Clone, PartialEq)]
1341pub enum SupervisorRouteConsumer {
1342 Reserved {
1343 module_id: String,
1344 },
1345 Direct {
1346 connection_id: u64,
1347 },
1348 Unknown {
1351 tag: String,
1352 body: OrderedJsonObject,
1353 },
1354}
1355
1356#[derive(Debug, Clone, PartialEq)]
1363pub enum StderrCaptureState {
1364 Captured,
1367 Incomplete { reason: String },
1369 NotCaptured { reason: String },
1371 Unknown {
1374 tag: String,
1375 body: OrderedJsonObject,
1376 },
1377}
1378
1379#[derive(Debug, Clone, PartialEq)]
1380pub enum StderrTailEntry {
1381 Line {
1382 text: String,
1383 truncated: bool,
1388 at_ms: Option<u64>,
1392 },
1393 ProcessStart,
1398 Unknown {
1401 tag: String,
1402 body: OrderedJsonObject,
1403 },
1404}
1405
1406#[derive(Debug, Serialize, Deserialize)]
1407#[serde(tag = "status", rename_all = "snake_case")]
1408enum ModuleDeclaredProvenanceWire {
1409 Reported { build: ManifestProvenance },
1410 Unverifiable,
1411}
1412
1413#[derive(Debug, Serialize, Deserialize)]
1414#[serde(tag = "status", rename_all = "snake_case")]
1415enum RunningImageAgreementWire {
1416 Match {
1417 evidence: RunningImageEvidence,
1418 },
1419 Mismatch {
1420 running: RunningImageEvidence,
1421 disk: RunningImageEvidence,
1422 },
1423 Unavailable {
1424 reason: RunningImageUnavailableReason,
1425 },
1426}
1427
1428#[derive(Debug, Serialize, Deserialize)]
1429#[serde(tag = "status", rename_all = "snake_case")]
1430enum ReloadPathAgreementWire {
1431 Match,
1432 Mismatch {
1433 configured: PathBuf,
1434 spawned_from: PathBuf,
1435 },
1436 Unavailable {
1437 reason: ReloadPathUnavailableReason,
1438 },
1439}
1440
1441#[derive(Debug, Serialize, Deserialize)]
1442#[serde(tag = "status", rename_all = "snake_case")]
1443enum LaunchSpecAgreementWire {
1444 Match,
1445 Mismatch,
1446 Unavailable { reason: LaunchSpecUnavailableReason },
1447}
1448
1449#[derive(Debug, Serialize, Deserialize)]
1450#[serde(tag = "method", rename_all = "snake_case")]
1451enum RunningImageEvidenceWire {
1452 LinuxProcSha256 {
1453 digest: String,
1454 },
1455 MacosSpawnInode {
1456 device: u64,
1457 inode: u64,
1458 },
1459 WindowsSpawnFileId {
1460 volume_serial_number: u64,
1461 file_id: [u8; 16],
1462 },
1463}
1464
1465#[derive(Debug, Serialize, Deserialize)]
1466#[serde(tag = "kind", rename_all = "snake_case")]
1467enum SupervisorRouteConsumerWire {
1468 Reserved { module_id: String },
1469 Direct { connection_id: u64 },
1470}
1471
1472#[derive(Debug, Serialize, Deserialize)]
1473#[serde(tag = "state", rename_all = "snake_case")]
1474enum StderrCaptureStateWire {
1475 Captured,
1476 Incomplete { reason: String },
1477 NotCaptured { reason: String },
1478}
1479
1480#[derive(Debug, Serialize, Deserialize)]
1481#[serde(tag = "status", rename_all = "snake_case")]
1482enum ChildResourceUsageWire {
1483 Measured(ChildResourceReading),
1484 Unavailable {
1485 reason: ChildResourceUnavailableReason,
1486 },
1487}
1488
1489#[derive(Debug, Serialize, Deserialize)]
1490#[serde(tag = "kind", rename_all = "snake_case")]
1491enum StderrTailEntryWire {
1492 Line {
1493 text: String,
1494 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1495 truncated: bool,
1496 #[serde(default, skip_serializing_if = "Option::is_none")]
1499 at_ms: Option<u64>,
1500 },
1501 ProcessStart,
1502}
1503
1504#[derive(Debug, Clone, PartialEq)]
1506pub enum OrderedJsonValue {
1507 Null,
1508 Bool(bool),
1509 Number(serde_json::Number),
1510 String(String),
1511 Array(Vec<Self>),
1512 Object(OrderedJsonObject),
1513}
1514
1515#[derive(Debug, Clone, PartialEq)]
1517pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1518
1519impl OrderedJsonObject {
1520 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1522 &self.0
1523 }
1524
1525 fn into_value(self) -> serde_json::Value {
1526 serde_json::Value::Object(
1527 self.0
1528 .into_iter()
1529 .map(|(key, value)| (key, value.into_value()))
1530 .collect(),
1531 )
1532 }
1533}
1534
1535impl OrderedJsonValue {
1536 fn into_value(self) -> serde_json::Value {
1537 match self {
1538 Self::Null => serde_json::Value::Null,
1539 Self::Bool(value) => serde_json::Value::Bool(value),
1540 Self::Number(value) => serde_json::Value::Number(value),
1541 Self::String(value) => serde_json::Value::String(value),
1542 Self::Array(values) => {
1543 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1544 }
1545 Self::Object(value) => value.into_value(),
1546 }
1547 }
1548}
1549
1550impl Serialize for OrderedJsonValue {
1551 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1552 where
1553 S: Serializer,
1554 {
1555 match self {
1556 Self::Null => serializer.serialize_unit(),
1557 Self::Bool(value) => serializer.serialize_bool(*value),
1558 Self::Number(value) => value.serialize(serializer),
1559 Self::String(value) => serializer.serialize_str(value),
1560 Self::Array(values) => values.serialize(serializer),
1561 Self::Object(value) => value.serialize(serializer),
1562 }
1563 }
1564}
1565
1566impl<'de> Deserialize<'de> for OrderedJsonValue {
1567 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1568 where
1569 D: Deserializer<'de>,
1570 {
1571 struct OrderedValueVisitor;
1572
1573 impl<'de> Visitor<'de> for OrderedValueVisitor {
1574 type Value = OrderedJsonValue;
1575
1576 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1577 formatter.write_str("a JSON value with ordered object members")
1578 }
1579
1580 fn visit_unit<E>(self) -> Result<Self::Value, E>
1581 where
1582 E: serde::de::Error,
1583 {
1584 Ok(OrderedJsonValue::Null)
1585 }
1586
1587 fn visit_none<E>(self) -> Result<Self::Value, E>
1588 where
1589 E: serde::de::Error,
1590 {
1591 Ok(OrderedJsonValue::Null)
1592 }
1593
1594 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1595 where
1596 D: Deserializer<'de>,
1597 {
1598 OrderedJsonValue::deserialize(deserializer)
1599 }
1600
1601 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1602 where
1603 E: serde::de::Error,
1604 {
1605 Ok(OrderedJsonValue::Bool(value))
1606 }
1607
1608 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1609 where
1610 E: serde::de::Error,
1611 {
1612 Ok(OrderedJsonValue::Number(value.into()))
1613 }
1614
1615 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1616 where
1617 E: serde::de::Error,
1618 {
1619 Ok(OrderedJsonValue::Number(value.into()))
1620 }
1621
1622 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1623 where
1624 E: serde::de::Error,
1625 {
1626 serde_json::Number::from_f64(value)
1627 .map(OrderedJsonValue::Number)
1628 .ok_or_else(|| E::custom("non-finite JSON number"))
1629 }
1630
1631 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1632 where
1633 E: serde::de::Error,
1634 {
1635 Ok(OrderedJsonValue::String(value.to_owned()))
1636 }
1637
1638 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1639 where
1640 E: serde::de::Error,
1641 {
1642 Ok(OrderedJsonValue::String(value))
1643 }
1644
1645 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1646 where
1647 A: SeqAccess<'de>,
1648 {
1649 let mut values = Vec::new();
1650 while let Some(value) = sequence.next_element()? {
1651 values.push(value);
1652 }
1653 Ok(OrderedJsonValue::Array(values))
1654 }
1655
1656 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1657 where
1658 A: MapAccess<'de>,
1659 {
1660 let mut entries = Vec::new();
1661 while let Some((key, value)) = map.next_entry()? {
1662 entries.push((key, value));
1663 }
1664 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1665 }
1666 }
1667
1668 deserializer.deserialize_any(OrderedValueVisitor)
1669 }
1670}
1671
1672impl Serialize for OrderedJsonObject {
1673 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1674 where
1675 S: Serializer,
1676 {
1677 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1678 for (key, value) in &self.0 {
1679 map.serialize_entry(key, value)?;
1680 }
1681 map.end()
1682 }
1683}
1684
1685impl<'de> Deserialize<'de> for OrderedJsonObject {
1686 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1687 where
1688 D: Deserializer<'de>,
1689 {
1690 struct OrderedObjectVisitor;
1691
1692 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1693 type Value = OrderedJsonObject;
1694
1695 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1696 formatter.write_str("an object with ordered JSON members")
1697 }
1698
1699 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1700 where
1701 A: MapAccess<'de>,
1702 {
1703 let mut entries = Vec::new();
1704 while let Some((key, value)) = map.next_entry()? {
1705 entries.push((key, value));
1706 }
1707 Ok(OrderedJsonObject(entries))
1708 }
1709 }
1710
1711 deserializer.deserialize_map(OrderedObjectVisitor)
1712 }
1713}
1714
1715fn read_tagged<'de, D>(
1716 deserializer: D,
1717 field: &'static str,
1718) -> Result<(String, OrderedJsonObject), D::Error>
1719where
1720 D: Deserializer<'de>,
1721{
1722 let body = OrderedJsonObject::deserialize(deserializer)?;
1723 let mut tag = None;
1724 for (key, value) in body.as_entries() {
1725 if key != field {
1726 continue;
1727 }
1728 if tag.is_some() {
1729 return Err(D::Error::custom(format!(
1730 "tagged object has duplicate `{field}` field"
1731 )));
1732 }
1733 let OrderedJsonValue::String(value) = value else {
1734 return Err(D::Error::custom(format!(
1735 "tagged object has no string `{field}` field"
1736 )));
1737 };
1738 tag = Some(value);
1739 }
1740 let Some(tag) = tag else {
1741 return Err(D::Error::custom(format!(
1742 "tagged object has no string `{field}` field"
1743 )));
1744 };
1745 Ok((tag.to_string(), body))
1746}
1747
1748fn read_ordered_tagged(
1749 value: OrderedJsonValue,
1750 field: &'static str,
1751) -> Result<(String, OrderedJsonObject), String> {
1752 let OrderedJsonValue::Object(body) = value else {
1753 return Err(format!("expected tagged object with `{field}` field"));
1754 };
1755 let mut tag = None;
1756 for (key, value) in body.as_entries() {
1757 if key != field {
1758 continue;
1759 }
1760 if tag.is_some() {
1761 return Err(format!("tagged object has duplicate `{field}` field"));
1762 }
1763 let OrderedJsonValue::String(value) = value else {
1764 return Err(format!("tagged object has no string `{field}` field"));
1765 };
1766 tag = Some(value);
1767 }
1768 let Some(tag) = tag else {
1769 return Err(format!("tagged object has no string `{field}` field"));
1770 };
1771 Ok((tag.to_string(), body))
1772}
1773
1774fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1775 body.as_entries()
1776 .iter()
1777 .find_map(|(key, value)| (key == field).then_some(value))
1778}
1779
1780fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1781 match ordered_field(body, field) {
1782 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1783 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1784 None => Err(format!("tagged object has no `{field}` field")),
1785 }
1786}
1787
1788fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1789 let (tag, body) = read_ordered_tagged(value, "method")?;
1790 match tag.as_str() {
1791 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1792 digest: ordered_string(&body, "digest")?,
1793 }),
1794 "macos_spawn_inode" => {
1795 let device = ordered_field(&body, "device")
1796 .and_then(|value| match value {
1797 OrderedJsonValue::Number(number) => number.as_u64(),
1798 _ => None,
1799 })
1800 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1801 let inode = ordered_field(&body, "inode")
1802 .and_then(|value| match value {
1803 OrderedJsonValue::Number(number) => number.as_u64(),
1804 _ => None,
1805 })
1806 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1807 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1808 }
1809 "windows_spawn_file_id" => {
1810 let wire: RunningImageEvidenceWire = serde_json::from_value(
1811 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1812 )
1813 .map_err(|error| error.to_string())?;
1814 match wire {
1815 RunningImageEvidenceWire::WindowsSpawnFileId {
1816 volume_serial_number,
1817 file_id,
1818 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1819 volume_serial_number,
1820 file_id,
1821 }),
1822 _ => unreachable!(),
1823 }
1824 }
1825 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1826 }
1827}
1828
1829impl Serialize for ModuleDeclaredProvenance {
1830 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1831 where
1832 S: Serializer,
1833 {
1834 match self {
1835 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1836 build: build.clone(),
1837 }
1838 .serialize(serializer),
1839 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1840 Self::Unknown { body, .. } => body.serialize(serializer),
1841 }
1842 }
1843}
1844
1845impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1846 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1847 where
1848 D: serde::Deserializer<'de>,
1849 {
1850 let (tag, value) = read_tagged(deserializer, "status")?;
1851 match tag.as_str() {
1852 "reported" => match serde_json::from_value(value.into_value())
1853 .map_err(D::Error::custom)?
1854 {
1855 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1856 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1857 },
1858 "unverifiable" => {
1859 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1860 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1861 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1862 }
1863 }
1864 _ => Ok(Self::Unknown { tag, body: value }),
1865 }
1866 }
1867}
1868
1869impl Serialize for RunningImageAgreement {
1870 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1871 where
1872 S: Serializer,
1873 {
1874 match self {
1875 Self::Match { evidence } => RunningImageAgreementWire::Match {
1876 evidence: evidence.clone(),
1877 }
1878 .serialize(serializer),
1879 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1880 running: running.clone(),
1881 disk: disk.clone(),
1882 }
1883 .serialize(serializer),
1884 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1885 reason: reason.clone(),
1886 }
1887 .serialize(serializer),
1888 Self::Unknown { body, .. } => body.serialize(serializer),
1889 }
1890 }
1891}
1892
1893impl Serialize for ReloadPathAgreement {
1894 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1895 where
1896 S: Serializer,
1897 {
1898 match self {
1899 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1900 Self::Mismatch {
1901 configured,
1902 spawned_from,
1903 } => ReloadPathAgreementWire::Mismatch {
1904 configured: configured.clone(),
1905 spawned_from: spawned_from.clone(),
1906 }
1907 .serialize(serializer),
1908 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1909 reason: reason.clone(),
1910 }
1911 .serialize(serializer),
1912 Self::Unknown { body, .. } => body.serialize(serializer),
1913 }
1914 }
1915}
1916
1917impl Serialize for LaunchSpecAgreement {
1918 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1919 where
1920 S: Serializer,
1921 {
1922 match self {
1923 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1924 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1925 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1926 reason: reason.clone(),
1927 }
1928 .serialize(serializer),
1929 Self::Unknown { body, .. } => body.serialize(serializer),
1930 }
1931 }
1932}
1933
1934impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1935 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1936 where
1937 D: Deserializer<'de>,
1938 {
1939 let (tag, body) = read_tagged(deserializer, "status")?;
1940 match tag.as_str() {
1941 "match" => Ok(Self::Match),
1942 "mismatch" => Ok(Self::Mismatch),
1943 "unavailable" => match serde_json::from_value(body.into_value())
1944 .map_err(D::Error::custom)?
1945 {
1946 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1947 _ => unreachable!(),
1948 },
1949 _ => Ok(Self::Unknown { tag, body }),
1950 }
1951 }
1952}
1953
1954impl<'de> Deserialize<'de> for ReloadPathAgreement {
1955 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1956 where
1957 D: Deserializer<'de>,
1958 {
1959 let (tag, body) = read_tagged(deserializer, "status")?;
1960 match tag.as_str() {
1961 "match" => Ok(Self::Match),
1962 "mismatch" => {
1963 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1964 ReloadPathAgreementWire::Mismatch {
1965 configured,
1966 spawned_from,
1967 } => Ok(Self::Mismatch {
1968 configured,
1969 spawned_from,
1970 }),
1971 _ => unreachable!(),
1972 }
1973 }
1974 "unavailable" => match serde_json::from_value(body.into_value())
1975 .map_err(D::Error::custom)?
1976 {
1977 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1978 _ => unreachable!(),
1979 },
1980 _ => Ok(Self::Unknown { tag, body }),
1981 }
1982 }
1983}
1984
1985impl<'de> Deserialize<'de> for RunningImageAgreement {
1986 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1987 where
1988 D: serde::Deserializer<'de>,
1989 {
1990 let (tag, value) = read_tagged(deserializer, "status")?;
1991 match tag.as_str() {
1992 "match" => Ok(Self::Match {
1993 evidence: decode_running_image_evidence(
1994 ordered_field(&value, "evidence")
1995 .cloned()
1996 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1997 )
1998 .map_err(D::Error::custom)?,
1999 }),
2000 "mismatch" => Ok(Self::Mismatch {
2001 running: decode_running_image_evidence(
2002 ordered_field(&value, "running")
2003 .cloned()
2004 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
2005 )
2006 .map_err(D::Error::custom)?,
2007 disk: decode_running_image_evidence(
2008 ordered_field(&value, "disk")
2009 .cloned()
2010 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
2011 )
2012 .map_err(D::Error::custom)?,
2013 }),
2014 "unavailable" => Ok(Self::Unavailable {
2015 reason: serde_json::from_value(
2016 ordered_field(&value, "reason")
2017 .cloned()
2018 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
2019 .into_value(),
2020 )
2021 .map_err(D::Error::custom)?,
2022 }),
2023 _ => Ok(Self::Unknown { tag, body: value }),
2024 }
2025 }
2026}
2027
2028impl Serialize for ChildResourceUsage {
2029 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2030 where
2031 S: Serializer,
2032 {
2033 match self {
2034 Self::Measured(reading) => {
2035 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
2036 }
2037 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
2038 reason: reason.clone(),
2039 }
2040 .serialize(serializer),
2041 Self::Unknown { body, .. } => body.serialize(serializer),
2042 }
2043 }
2044}
2045
2046impl<'de> Deserialize<'de> for ChildResourceUsage {
2047 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2048 where
2049 D: Deserializer<'de>,
2050 {
2051 let (tag, body) = read_tagged(deserializer, "status")?;
2052 match tag.as_str() {
2053 "measured" | "unavailable" => {
2054 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2055 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
2056 ChildResourceUsageWire::Unavailable { reason } => {
2057 Ok(Self::Unavailable { reason })
2058 }
2059 }
2060 }
2061 _ => Ok(Self::Unknown { tag, body }),
2062 }
2063 }
2064}
2065
2066impl Serialize for RunningImageEvidence {
2067 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2068 where
2069 S: Serializer,
2070 {
2071 match self {
2072 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
2073 digest: digest.clone(),
2074 }
2075 .serialize(serializer),
2076 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
2077 device: *device,
2078 inode: *inode,
2079 }
2080 .serialize(serializer),
2081 Self::WindowsSpawnFileId {
2082 volume_serial_number,
2083 file_id,
2084 } => RunningImageEvidenceWire::WindowsSpawnFileId {
2085 volume_serial_number: *volume_serial_number,
2086 file_id: *file_id,
2087 }
2088 .serialize(serializer),
2089 Self::Unknown { body, .. } => body.serialize(serializer),
2090 }
2091 }
2092}
2093
2094impl<'de> Deserialize<'de> for RunningImageEvidence {
2095 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2096 where
2097 D: serde::Deserializer<'de>,
2098 {
2099 let (tag, value) = read_tagged(deserializer, "method")?;
2100 match tag.as_str() {
2101 "linux_proc_sha256" => {
2102 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2103 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
2104 Ok(Self::LinuxProcSha256 { digest })
2105 }
2106 _ => unreachable!(),
2107 }
2108 }
2109 "macos_spawn_inode" => {
2110 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2111 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
2112 Ok(Self::MacosSpawnInode { device, inode })
2113 }
2114 _ => unreachable!(),
2115 }
2116 }
2117 "windows_spawn_file_id" => {
2118 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2119 RunningImageEvidenceWire::WindowsSpawnFileId {
2120 volume_serial_number,
2121 file_id,
2122 } => Ok(Self::WindowsSpawnFileId {
2123 volume_serial_number,
2124 file_id,
2125 }),
2126 _ => unreachable!(),
2127 }
2128 }
2129 _ => Ok(Self::Unknown { tag, body: value }),
2130 }
2131 }
2132}
2133
2134impl Serialize for SupervisorRouteConsumer {
2135 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2136 where
2137 S: Serializer,
2138 {
2139 match self {
2140 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
2141 module_id: module_id.clone(),
2142 }
2143 .serialize(serializer),
2144 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
2145 connection_id: *connection_id,
2146 }
2147 .serialize(serializer),
2148 Self::Unknown { body, .. } => body.serialize(serializer),
2149 }
2150 }
2151}
2152
2153impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
2154 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2155 where
2156 D: serde::Deserializer<'de>,
2157 {
2158 let (tag, value) = read_tagged(deserializer, "kind")?;
2159 match tag.as_str() {
2160 "reserved" => {
2161 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2162 SupervisorRouteConsumerWire::Reserved { module_id } => {
2163 Ok(Self::Reserved { module_id })
2164 }
2165 _ => unreachable!(),
2166 }
2167 }
2168 "direct" => {
2169 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2170 SupervisorRouteConsumerWire::Direct { connection_id } => {
2171 Ok(Self::Direct { connection_id })
2172 }
2173 _ => unreachable!(),
2174 }
2175 }
2176 _ => Ok(Self::Unknown { tag, body: value }),
2177 }
2178 }
2179}
2180
2181impl Serialize for StderrCaptureState {
2182 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2183 where
2184 S: Serializer,
2185 {
2186 match self {
2187 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
2188 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
2189 reason: reason.clone(),
2190 }
2191 .serialize(serializer),
2192 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
2193 reason: reason.clone(),
2194 }
2195 .serialize(serializer),
2196 Self::Unknown { body, .. } => body.serialize(serializer),
2197 }
2198 }
2199}
2200
2201impl<'de> Deserialize<'de> for StderrCaptureState {
2202 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2203 where
2204 D: serde::Deserializer<'de>,
2205 {
2206 let (tag, value) = read_tagged(deserializer, "state")?;
2207 match tag.as_str() {
2208 "captured" => {
2209 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2210 StderrCaptureStateWire::Captured => Ok(Self::Captured),
2211 _ => unreachable!(),
2212 }
2213 }
2214 "incomplete" => match serde_json::from_value(value.into_value())
2215 .map_err(D::Error::custom)?
2216 {
2217 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
2218 _ => unreachable!(),
2219 },
2220 "not_captured" => match serde_json::from_value(value.into_value())
2221 .map_err(D::Error::custom)?
2222 {
2223 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
2224 _ => unreachable!(),
2225 },
2226 _ => Ok(Self::Unknown { tag, body: value }),
2227 }
2228 }
2229}
2230
2231impl Serialize for StderrTailEntry {
2232 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2233 where
2234 S: Serializer,
2235 {
2236 match self {
2237 Self::Line {
2238 text,
2239 truncated,
2240 at_ms,
2241 } => StderrTailEntryWire::Line {
2242 text: text.clone(),
2243 truncated: *truncated,
2244 at_ms: *at_ms,
2245 }
2246 .serialize(serializer),
2247 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
2248 Self::Unknown { body, .. } => body.serialize(serializer),
2249 }
2250 }
2251}
2252
2253impl<'de> Deserialize<'de> for StderrTailEntry {
2254 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2255 where
2256 D: serde::Deserializer<'de>,
2257 {
2258 let (tag, value) = read_tagged(deserializer, "kind")?;
2259 match tag.as_str() {
2260 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2261 StderrTailEntryWire::Line {
2262 text,
2263 truncated,
2264 at_ms,
2265 } => Ok(Self::Line {
2266 text,
2267 truncated,
2268 at_ms,
2269 }),
2270 _ => unreachable!(),
2271 },
2272 "process_start" => {
2273 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2274 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
2275 _ => unreachable!(),
2276 }
2277 }
2278 _ => Ok(Self::Unknown { tag, body: value }),
2279 }
2280 }
2281}
2282
2283fn is_zero_u64(value: &u64) -> bool {
2284 *value == 0
2285}
2286
2287fn default_true() -> bool {
2288 true
2289}
2290
2291#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2293pub struct TerminalHistory {
2294 pub daemon_started_at_ms: u64,
2296 pub entries: Vec<TerminalEntry>,
2297 #[serde(default, skip_serializing_if = "is_zero_u64")]
2300 pub dropped: u64,
2301 #[serde(default, skip_serializing_if = "is_zero_u64")]
2304 pub journal_skipped_lines: u64,
2305 #[serde(default, skip_serializing_if = "is_zero_u64")]
2307 pub journal_read_errors: u64,
2308 #[serde(default, skip_serializing_if = "is_zero_u64")]
2310 pub journal_write_failures: u64,
2311}
2312
2313#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2315pub struct TerminalEntry {
2316 #[serde(default, skip_serializing_if = "Option::is_none")]
2319 pub daemon_incarnation: Option<String>,
2320 #[serde(default, skip_serializing_if = "Option::is_none")]
2321 pub exit_code: Option<i32>,
2322 #[serde(default, skip_serializing_if = "Option::is_none")]
2323 pub exit_signal: Option<i32>,
2324 pub at_ms: u64,
2325 pub disposition: TerminalDisposition,
2326 #[serde(default, skip_serializing_if = "Option::is_none")]
2330 pub exit_kind: Option<TerminalExitKind>,
2331 #[serde(default, skip_serializing_if = "Option::is_none")]
2338 pub disposition_detail: Option<String>,
2339}
2340
2341#[derive(Debug, Clone, PartialEq, Eq)]
2346pub enum TerminalExitKind {
2347 Clean,
2348 Crash,
2349 DeliberateSeverance,
2350 Unknown(String),
2351}
2352
2353impl TerminalExitKind {
2354 fn wire_name(&self) -> &str {
2355 match self {
2356 Self::Clean => "clean",
2357 Self::Crash => "crash",
2358 Self::DeliberateSeverance => "deliberate_severance",
2359 Self::Unknown(value) => value,
2360 }
2361 }
2362}
2363
2364impl Serialize for TerminalExitKind {
2365 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2366 where
2367 S: serde::Serializer,
2368 {
2369 serializer.serialize_str(self.wire_name())
2370 }
2371}
2372
2373impl<'de> Deserialize<'de> for TerminalExitKind {
2374 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2375 where
2376 D: serde::Deserializer<'de>,
2377 {
2378 let value = String::deserialize(deserializer)?;
2379 Ok(match value.as_str() {
2380 "clean" => Self::Clean,
2381 "crash" => Self::Crash,
2382 "deliberate_severance" => Self::DeliberateSeverance,
2383 _ => Self::Unknown(value),
2384 })
2385 }
2386}
2387
2388open_string_enum! {
2389 TerminalDisposition {
2391 Stopped => "stopped",
2392 Disabled => "disabled",
2393 Failed => "failed",
2394 Restarting => "restarting",
2395 DaemonShutdown => "daemon_shutdown",
2400 }
2401}
2402
2403#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2404#[serde(rename_all = "snake_case")]
2405pub enum PollKind {
2406 Status,
2407 Liveness,
2408}
2409
2410#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2422#[non_exhaustive]
2423pub struct CatalogEntry {
2424 pub module_id: String,
2425 #[serde(default, skip_serializing_if = "Option::is_none")]
2427 pub display_name: Option<String>,
2428 #[serde(default = "default_true")]
2439 pub ready: bool,
2440 #[serde(default, skip_serializing_if = "Option::is_none")]
2444 pub not_ready: Option<NotReadyReason>,
2445 #[serde(default, skip_serializing_if = "Option::is_none")]
2466 pub module_version: Option<String>,
2467 #[serde(default, skip_serializing_if = "Option::is_none")]
2470 pub provenance: Option<ManifestProvenance>,
2471 pub roles: Vec<ProviderRole>,
2472 pub control_ops: Vec<String>,
2473 #[serde(default, skip_serializing_if = "Option::is_none")]
2478 pub capabilities: Option<CapabilityDeclarations>,
2479 #[serde(default, skip_serializing_if = "Option::is_none")]
2482 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2483 #[serde(default, skip_serializing_if = "Option::is_none")]
2487 pub events: Option<Vec<EventDeclaration>>,
2488 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2491 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2492 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2495 pub operation_payload: BTreeMap<String, OperationPayload>,
2496 #[serde(default, skip_serializing_if = "Option::is_none")]
2502 pub flow_operations: Option<Vec<String>>,
2503 #[serde(default, skip_serializing_if = "Option::is_none")]
2505 pub operation_deferral: Option<BTreeMap<String, bool>>,
2506 #[serde(default, skip_serializing_if = "Option::is_none")]
2512 pub confirm_operations: Option<Vec<String>>,
2513 #[serde(default, skip_serializing_if = "Option::is_none")]
2516 pub rich_ui: Option<RichUiDescriptor>,
2517 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2520 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2521 #[serde(default, skip_serializing_if = "is_false")]
2526 pub nonce_verified: bool,
2527 #[serde(default, skip_serializing_if = "Option::is_none")]
2530 pub incarnation: Option<String>,
2531 #[serde(
2532 default,
2533 skip_serializing_if = "Option::is_none",
2534 deserialize_with = "deserialize_optional_attestation_integer"
2535 )]
2536 pub spawn: Option<u64>,
2537 #[serde(default, skip_serializing_if = "Option::is_none")]
2538 pub first_party: Option<bool>,
2539 #[serde(default, skip_serializing_if = "Option::is_none")]
2540 pub origin: Option<CatalogOrigin>,
2541 #[serde(default, skip_serializing_if = "Option::is_none")]
2542 pub requested_declarations_digest: Option<String>,
2543 #[serde(default, skip_serializing_if = "Option::is_none")]
2544 pub approved_declarations_digest: Option<String>,
2545 #[serde(default, skip_serializing_if = "Option::is_none")]
2548 pub approved_declarations: Option<ProviderDeclarations>,
2549 #[serde(default, skip_serializing_if = "Option::is_none")]
2550 pub requested_declarations: Option<ProviderDeclarations>,
2551}
2552
2553impl CatalogEntry {
2554 #[must_use]
2556 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2557 self.display_name = display_name;
2558 self
2559 }
2560
2561 #[must_use]
2563 pub fn new(
2564 module_id: impl Into<String>,
2565 roles: Vec<ProviderRole>,
2566 control_ops: Vec<String>,
2567 ) -> Self {
2568 Self {
2569 module_id: module_id.into(),
2570 ready: default_true(),
2571 display_name: None,
2572 not_ready: None,
2573 module_version: None,
2574 provenance: None,
2575 roles,
2576 control_ops,
2577 capabilities: None,
2578 self_signals: None,
2579 events: None,
2580 operation_delivery: BTreeMap::new(),
2581 operation_payload: BTreeMap::new(),
2582 flow_operations: None,
2583 operation_deferral: None,
2584 confirm_operations: None,
2585 rich_ui: None,
2586 role_declarations: BTreeMap::new(),
2587 nonce_verified: false,
2588 incarnation: None,
2589 spawn: None,
2590 first_party: None,
2591 origin: None,
2592 requested_declarations_digest: None,
2593 approved_declarations_digest: None,
2594 approved_declarations: None,
2595 requested_declarations: None,
2596 }
2597 }
2598
2599 #[must_use]
2601 pub fn with_operation_payload(
2602 mut self,
2603 operation_payload: BTreeMap<String, OperationPayload>,
2604 ) -> Self {
2605 self.operation_payload = operation_payload;
2606 self
2607 }
2608
2609 #[must_use]
2612 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2613 self.flow_operations = flow_operations;
2614 self
2615 }
2616
2617 #[must_use]
2619 pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
2620 self.operation_deferral = operations;
2621 self
2622 }
2623
2624 #[must_use]
2627 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2628 self.confirm_operations = confirm_operations;
2629 self
2630 }
2631
2632 #[must_use]
2634 pub fn with_ready(mut self, ready: bool) -> Self {
2635 self.ready = ready;
2636 self
2637 }
2638
2639 #[must_use]
2641 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2642 self.not_ready = not_ready;
2643 self
2644 }
2645
2646 #[must_use]
2648 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2649 self.module_version = module_version;
2650 self
2651 }
2652
2653 #[must_use]
2655 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2656 self.provenance = provenance;
2657 self
2658 }
2659
2660 #[must_use]
2662 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2663 self.capabilities = capabilities;
2664 self
2665 }
2666
2667 #[must_use]
2669 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2670 self.self_signals = self_signals;
2671 self
2672 }
2673
2674 #[must_use]
2676 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2677 self.events = events;
2678 self
2679 }
2680
2681 #[must_use]
2684 pub fn with_operation_delivery(
2685 mut self,
2686 operation_delivery: BTreeMap<String, OperationDelivery>,
2687 ) -> Self {
2688 self.operation_delivery = operation_delivery;
2689 self
2690 }
2691
2692 #[must_use]
2694 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2695 self.rich_ui = rich_ui;
2696 self
2697 }
2698
2699 #[must_use]
2701 pub fn with_role_declarations(
2702 mut self,
2703 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2704 ) -> Self {
2705 self.role_declarations = role_declarations;
2706 self
2707 }
2708
2709 #[must_use]
2711 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2712 self.nonce_verified = nonce_verified;
2713 self
2714 }
2715}
2716
2717fn is_false(value: &bool) -> bool {
2718 !value
2719}
2720
2721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2723pub struct NotReadyReason {
2724 pub reason: String,
2729 #[serde(default, skip_serializing_if = "Option::is_none")]
2732 pub capability: Option<String>,
2733}
2734
2735impl NotReadyReason {
2736 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2737 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2738}
2739
2740#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2741pub struct CapabilityRequirementStatus {
2742 pub consumer: String,
2743 pub capability: String,
2744 pub need: String,
2745 pub verdict: String,
2746 pub episode_seq: u64,
2747 pub config_satisfiable: bool,
2748 pub runtime_available: bool,
2749 pub detail: String,
2750}
2751
2752#[non_exhaustive]
2757#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2758#[serde(rename_all = "snake_case")]
2759pub enum PendingModuleApply {
2760 NextSupervision,
2761 WithNextLaunchOrHealthChange,
2762 DaemonRestart,
2763 ConfigGate,
2764 #[serde(other)]
2765 Other,
2766}
2767
2768#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2770pub struct SupervisorPendingField {
2771 pub field: String,
2772 pub applies: PendingModuleApply,
2773 #[serde(default, skip_serializing_if = "Option::is_none")]
2774 pub value: Option<serde_json::Value>,
2775}
2776
2777#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2778pub struct SupervisorPendingModule {
2779 pub module_id: String,
2780 pub fields: Vec<SupervisorPendingField>,
2781}
2782
2783#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2784pub struct SupervisorRescanResult {
2785 pub added: Vec<String>,
2786 pub removed: Vec<String>,
2787 pub changed_pending_reload: Vec<String>,
2788 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2790 pub changed_pending: Vec<SupervisorPendingModule>,
2791 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2804 pub enabled_changes: Vec<String>,
2805 pub unchanged: u32,
2806 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2814 pub preview: bool,
2815 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2833 pub restart_required: Vec<String>,
2834 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2838 pub capability_warnings: Vec<String>,
2839 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2846 pub module_actions: Vec<RescanModuleAction>,
2847 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2851 pub earlier_pending: Vec<String>,
2852 #[serde(default, skip_serializing_if = "Option::is_none")]
2855 pub expect: Option<RescanExpect>,
2856}
2857
2858#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2874#[serde(rename_all = "snake_case")]
2875pub enum ModuleProtocol {
2876 #[default]
2880 Subc,
2881 None,
2890}
2891
2892#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2904#[non_exhaustive]
2905pub struct SupervisorEntry {
2906 #[serde(default, skip_serializing_if = "Option::is_none")]
2908 pub script: Option<ScriptModuleStatus>,
2909 #[serde(default, skip_serializing_if = "Option::is_none")]
2912 pub waiting_for_previous_pid: Option<u32>,
2913 pub module_id: String,
2914 pub state: String,
2915 #[serde(default, skip_serializing_if = "Option::is_none")]
2919 pub admission_refused: Option<String>,
2920 #[serde(default, skip_serializing_if = "Option::is_none")]
2924 pub next_retry_at_ms: Option<u64>,
2925 pub enabled: bool,
2926 #[serde(default, skip_serializing_if = "Option::is_none")]
2929 pub configured_enabled: Option<bool>,
2930 pub live: bool,
2940 #[serde(default)]
2944 pub protocol: ModuleProtocol,
2945 #[serde(default, skip_serializing_if = "Option::is_none")]
2948 pub launch_nonce_env: Option<bool>,
2949 #[serde(default, skip_serializing_if = "Option::is_none")]
2955 pub launch_nonce_source: Option<String>,
2956 pub health: SupervisorHealthStatus,
2957 #[serde(default, skip_serializing_if = "Option::is_none")]
2960 pub pending_reload: Option<PendingReloadVerdict>,
2961 #[serde(default)]
2967 pub last_probe_ms: Option<u64>,
2968 #[serde(default, skip_serializing_if = "Option::is_none")]
2972 pub last_exit_code: Option<i32>,
2973 #[serde(default, skip_serializing_if = "Option::is_none")]
2977 pub last_exit_signal: Option<i32>,
2978 #[serde(default, skip_serializing_if = "Option::is_none")]
2982 pub last_exit_ms: Option<u64>,
2983 #[serde(default, skip_serializing_if = "Option::is_none")]
2986 pub last_exit_kind: Option<TerminalExitKind>,
2987 #[serde(default, skip_serializing_if = "Option::is_none")]
3004 pub restart_count: Option<u32>,
3005 #[serde(default, skip_serializing_if = "Option::is_none")]
3008 pub max_restarts: Option<u32>,
3009 #[serde(default, skip_serializing_if = "Option::is_none")]
3012 pub lifetime_restarts: Option<u32>,
3013 #[serde(default, skip_serializing_if = "Option::is_none")]
3017 pub spawn_generation: Option<u64>,
3018 #[serde(default, skip_serializing_if = "Option::is_none")]
3028 pub restart_window_secs: Option<u64>,
3029 #[serde(default, skip_serializing_if = "Option::is_none")]
3033 pub drain_timeout_ms: Option<u64>,
3034 #[serde(default, skip_serializing_if = "Option::is_none")]
3037 pub restart_backoff_ms: Option<u64>,
3038 #[serde(default, skip_serializing_if = "Option::is_none")]
3041 pub restart_max_backoff_ms: Option<u64>,
3042 #[serde(default, skip_serializing_if = "Option::is_none")]
3055 pub resources: Option<ChildResourceUsage>,
3056 #[serde(default, skip_serializing_if = "Option::is_none")]
3058 pub tree: Option<TreeReading>,
3059 #[serde(default, skip_serializing_if = "Option::is_none")]
3065 pub tree_unavailable: Option<String>,
3066 #[serde(default, skip_serializing_if = "Option::is_none")]
3068 pub cpu_last_hour: Option<CpuLastHour>,
3069 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3071 pub pending: Vec<SupervisorPendingField>,
3072}
3073
3074impl SupervisorEntry {
3075 #[must_use]
3076 pub fn with_script(mut self, script: Option<ScriptModuleStatus>) -> Self {
3077 self.script = script;
3078 self
3079 }
3080 #[must_use]
3082 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3083 self.next_retry_at_ms = next_retry_at_ms;
3084 self
3085 }
3086
3087 #[must_use]
3089 pub fn new(
3090 module_id: impl Into<String>,
3091 state: impl Into<String>,
3092 enabled: bool,
3093 live: bool,
3094 health: SupervisorHealthStatus,
3095 ) -> Self {
3096 Self {
3097 module_id: module_id.into(),
3098 script: None,
3099 state: state.into(),
3100 admission_refused: None,
3101 next_retry_at_ms: None,
3102 waiting_for_previous_pid: None,
3103 enabled,
3104 configured_enabled: None,
3105 live,
3106 protocol: ModuleProtocol::default(),
3107 launch_nonce_env: None,
3108 launch_nonce_source: None,
3109 health,
3110 pending_reload: None,
3111 last_probe_ms: None,
3112 last_exit_code: None,
3113 last_exit_signal: None,
3114 last_exit_ms: None,
3115 last_exit_kind: None,
3116 restart_count: None,
3117 max_restarts: None,
3118 lifetime_restarts: None,
3119 spawn_generation: None,
3120 restart_window_secs: None,
3121 drain_timeout_ms: None,
3122 restart_backoff_ms: None,
3123 restart_max_backoff_ms: None,
3124 resources: None,
3125 tree: None,
3126 tree_unavailable: None,
3127 cpu_last_hour: None,
3128 pending: Vec::new(),
3129 }
3130 }
3131
3132 #[must_use]
3134 pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3135 self.admission_refused = reason;
3136 self
3137 }
3138
3139 #[must_use]
3141 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3142 self.protocol = protocol;
3143 self
3144 }
3145
3146 #[must_use]
3148 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3149 self.configured_enabled = configured_enabled;
3150 self
3151 }
3152
3153 #[must_use]
3155 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3156 self.launch_nonce_env = launch_nonce_env;
3157 self
3158 }
3159
3160 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3161 self.launch_nonce_source = source;
3162 self
3163 }
3164
3165 #[must_use]
3166 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3167 self.waiting_for_previous_pid = pid;
3168 self
3169 }
3170
3171 #[must_use]
3173 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3174 self.pending_reload = pending_reload;
3175 self
3176 }
3177
3178 #[must_use]
3180 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3181 self.last_probe_ms = last_probe_ms;
3182 self
3183 }
3184
3185 #[must_use]
3187 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3188 self.last_exit_code = last_exit_code;
3189 self
3190 }
3191
3192 #[must_use]
3194 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3195 self.last_exit_signal = last_exit_signal;
3196 self
3197 }
3198
3199 #[must_use]
3201 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3202 self.last_exit_ms = last_exit_ms;
3203 self
3204 }
3205
3206 #[must_use]
3208 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3209 self.last_exit_kind = last_exit_kind;
3210 self
3211 }
3212
3213 #[must_use]
3215 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3216 self.restart_count = restart_count;
3217 self
3218 }
3219
3220 #[must_use]
3222 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3223 self.max_restarts = max_restarts;
3224 self
3225 }
3226
3227 #[must_use]
3229 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3230 self.lifetime_restarts = lifetime_restarts;
3231 self
3232 }
3233
3234 #[must_use]
3236 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3237 self.spawn_generation = spawn_generation;
3238 self
3239 }
3240
3241 #[must_use]
3243 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3244 self.restart_window_secs = restart_window_secs;
3245 self
3246 }
3247
3248 #[must_use]
3250 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3251 self.drain_timeout_ms = drain_timeout_ms;
3252 self
3253 }
3254
3255 #[must_use]
3257 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3258 self.restart_backoff_ms = restart_backoff_ms;
3259 self
3260 }
3261
3262 #[must_use]
3264 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3265 self.restart_max_backoff_ms = restart_max_backoff_ms;
3266 self
3267 }
3268
3269 #[must_use]
3271 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3272 self.resources = resources;
3273 self
3274 }
3275
3276 #[must_use]
3278 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3279 self.tree = tree;
3280 self
3281 }
3282
3283 #[must_use]
3285 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3286 self.tree_unavailable = reason;
3287 self
3288 }
3289}
3290
3291#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3293pub struct ScriptModuleStatus {
3294 pub runtime: String,
3295 pub bun_version: Option<String>,
3296 pub path: PathBuf,
3297 pub sha256: Option<String>,
3298 pub size: Option<u64>,
3299 pub needs_review: bool,
3300}
3301
3302#[cfg(test)]
3303mod script_status_tests {
3304 use super::*;
3305
3306 #[test]
3307 fn script_status_roundtrips_and_old_supervisor_entries_remain_readable() {
3308 let old = SupervisorEntry::new(
3309 "example",
3310 "running",
3311 true,
3312 true,
3313 SupervisorHealthStatus::Unknown,
3314 );
3315 let value = serde_json::to_value(&old).unwrap();
3316 assert!(value.get("script").is_none());
3317 assert!(serde_json::from_value::<SupervisorEntry>(value)
3318 .unwrap()
3319 .script
3320 .is_none());
3321 let current = old.with_script(Some(ScriptModuleStatus {
3322 runtime: "bun".into(),
3323 bun_version: None,
3324 path: "bundle.js".into(),
3325 sha256: Some("ab".repeat(32)),
3326 size: Some(3),
3327 needs_review: true,
3328 }));
3329 let decoded: SupervisorEntry =
3330 serde_json::from_slice(&serde_json::to_vec(¤t).unwrap()).unwrap();
3331 assert_eq!(decoded, current);
3332 }
3333}
3334
3335#[derive(Debug, Clone, PartialEq)]
3338pub enum ChildResourceUsage {
3339 Measured(ChildResourceReading),
3340 Unavailable {
3341 reason: ChildResourceUnavailableReason,
3342 },
3343 Unknown {
3346 tag: String,
3347 body: OrderedJsonObject,
3348 },
3349}
3350
3351#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3354#[non_exhaustive]
3355pub struct ChildResourceReading {
3356 pub memory_bytes: u64,
3359 pub memory_kind: ChildMemoryKind,
3360 #[serde(default, skip_serializing_if = "Option::is_none")]
3363 pub swap_bytes: Option<u64>,
3364 pub cpu_user_ms: u64,
3368 pub cpu_system_ms: u64,
3371}
3372
3373impl ChildResourceReading {
3374 #[must_use]
3376 pub fn new(
3377 memory_bytes: u64,
3378 memory_kind: ChildMemoryKind,
3379 cpu_user_ms: u64,
3380 cpu_system_ms: u64,
3381 ) -> Self {
3382 Self {
3383 memory_bytes,
3384 memory_kind,
3385 cpu_user_ms,
3386 cpu_system_ms,
3387 swap_bytes: None,
3388 }
3389 }
3390
3391 #[must_use]
3393 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3394 self.swap_bytes = swap_bytes;
3395 self
3396 }
3397}
3398
3399open_string_enum! {
3400 ChildMemoryKind {
3402 PhysFootprint => "phys_footprint",
3406 ResidentSet => "resident_set",
3409 WindowsWorkingSet => "windows_working_set",
3412 }
3413}
3414
3415open_string_enum! {
3416 ChildResourceUnavailableReason {
3418 NotRunning => "not_running",
3420 UnsupportedPlatform => "unsupported_platform",
3422 Unreadable => "unreadable",
3425 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3428 }
3429}
3430
3431#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3432#[serde(rename_all = "snake_case")]
3433pub enum SupervisorHealthStatus {
3434 Ok,
3435 Degraded,
3436 Failing,
3437 Unresponsive,
3438 Unknown,
3439}
3440
3441#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3442pub struct SupervisorHealthEntry {
3443 pub module_id: String,
3444 pub status: SupervisorHealthStatus,
3445 #[serde(default, skip_serializing_if = "Option::is_none")]
3451 pub detail: Option<String>,
3452 #[serde(default, skip_serializing_if = "Option::is_none")]
3457 pub metrics: Option<serde_json::Value>,
3458 pub consecutive_failures: u32,
3459 #[serde(default)]
3462 pub late_answer_count: u64,
3463 #[serde(default, skip_serializing_if = "Option::is_none")]
3465 pub last_late_answer_latency_ms: Option<u64>,
3466 #[serde(default)]
3471 pub last_action: Option<String>,
3472 #[serde(default)]
3475 pub last_action_ms: Option<u64>,
3476 #[serde(default, skip_serializing_if = "Option::is_none")]
3489 pub last_probe_ms: Option<u64>,
3490}
3491
3492#[cfg(test)]
3493mod tests {
3494 #[test]
3495 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3496 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3497 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3498 assert_eq!(decoded.configured_enabled, None);
3499 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3500 }
3501
3502 #[test]
3503 fn configured_enabled_values_round_trip_in_list() {
3504 for enabled in [false, true] {
3505 let entry = SupervisorEntry::new(
3506 "provider",
3507 "running",
3508 true,
3509 true,
3510 SupervisorHealthStatus::Unknown,
3511 )
3512 .with_configured_enabled(Some(enabled));
3513 let entry_json = serde_json::to_value(&entry).unwrap();
3514 assert_eq!(entry_json["configured_enabled"], enabled);
3515 assert_eq!(
3516 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3517 entry
3518 );
3519 }
3520 }
3521
3522 #[test]
3523 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3524 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3525 volume_serial_number: u64::MAX,
3526 file_id: [
3527 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3528 ],
3529 };
3530 let agreement = super::RunningImageAgreement::Match { evidence };
3531 let encoded = serde_json::to_string(&agreement).unwrap();
3532 assert!(encoded.contains("windows_spawn_file_id"));
3533 assert_eq!(
3534 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3535 agreement
3536 );
3537 }
3538
3539 #[test]
3540 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3541 assert_eq!(
3542 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3543 device: 7,
3544 inode: 11
3545 })
3546 .unwrap(),
3547 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3548 );
3549 assert_eq!(
3550 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3551 digest: "abc".to_owned()
3552 })
3553 .unwrap(),
3554 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3555 );
3556 }
3557 use super::*;
3558 use subc_protocol::{BindIdentity, RouteTarget};
3559
3560 #[test]
3561 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3562 let entry = TerminalEntry {
3563 daemon_incarnation: Some("daemon-before-restart".into()),
3564 exit_code: Some(1),
3565 exit_signal: None,
3566 at_ms: 1_700_000_000_123,
3567 disposition: TerminalDisposition::Restarting,
3568 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3569 disposition_detail: None,
3570 };
3571 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3572 assert_eq!(
3573 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3574 ["exit_kind"],
3575 "deliberate_severance"
3576 );
3577
3578 #[derive(serde::Deserialize)]
3579 struct LegacyTerminalEntry {
3580 exit_code: Option<i32>,
3581 exit_signal: Option<i32>,
3582 at_ms: u64,
3583 disposition: TerminalDisposition,
3584 }
3585
3586 let decoded: LegacyTerminalEntry =
3587 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3588 assert_eq!(decoded.exit_code, Some(1));
3589 assert_eq!(decoded.exit_signal, None);
3590 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3591 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3592
3593 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3594 let future: TerminalEntry =
3595 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3596 assert_eq!(
3597 future.exit_kind,
3598 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3599 );
3600 }
3601
3602 #[test]
3603 fn terminal_incarnation_is_optional_for_older_daemons() {
3604 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3605 "at_ms": 123,
3606 "disposition": "stopped"
3607 }))
3608 .unwrap();
3609 let encoded = serde_json::to_value(&entry).unwrap();
3610 assert_eq!(
3611 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3612 (None, None)
3613 );
3614 }
3615
3616 #[test]
3617 fn route_poll_uses_kind_field() {
3618 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3619 route_channel: 7,
3620 route_epoch: 11,
3621 kind: PollKind::Status,
3622 })
3623 .unwrap();
3624
3625 assert_eq!(body["op"], "route.poll");
3626 assert_eq!(body["route_epoch"], 11);
3627 assert_eq!(body["kind"], "status");
3628 assert!(body.get("op").is_some());
3629 }
3630
3631 #[test]
3632 fn route_open_is_internally_tagged() {
3633 let request = ClientControlRequest::RouteOpen {
3634 busy_refusals: None,
3635 target: RouteTarget::ToolProvider {
3636 module_id: "aft".to_string(),
3637 },
3638 identity: BindIdentity::new("opencode", "session-1"),
3639 consumer_identity: None,
3640 consumer_capabilities: None,
3641 role_versions: None,
3642 admission_facts: None,
3643 scope: None,
3644 };
3645
3646 let body = serde_json::to_value(request).unwrap();
3647 assert_eq!(body["op"], "route.open");
3648 assert_eq!(body["target"]["kind"], "tool_provider");
3649 assert!(body.get("consumer_identity").is_none());
3650 assert!(body.get("consumer_capabilities").is_none());
3651 assert!(body.get("role_versions").is_none());
3652 }
3653
3654 #[test]
3655 fn route_open_without_optional_fields_still_decodes() {
3656 let body = serde_json::json!({
3657 "op": "route.open",
3658 "target": { "kind": "tool_provider", "module_id": "aft" },
3659 "identity": {
3660 "project_root": "/tmp/project",
3661 "harness": "opencode",
3662 "session": "session-1"
3663 }
3664 });
3665
3666 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3667 let ClientControlRequest::RouteOpen {
3668 consumer_identity,
3669 consumer_capabilities,
3670 role_versions,
3671 admission_facts,
3672 ..
3673 } = decoded
3674 else {
3675 panic!("decoded wrong request variant");
3676 };
3677 assert_eq!(consumer_identity, None);
3678 assert_eq!(consumer_capabilities, None);
3679 assert_eq!(role_versions, None);
3680 assert_eq!(admission_facts, None);
3681 }
3682
3683 #[test]
3684 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3685 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3686 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3687 match decoded {
3688 ClientControlPush::RouteClosed {
3689 excluded_subscriptions,
3690 terminal,
3691 ..
3692 } => {
3693 assert_eq!(excluded_subscriptions, 0);
3694 assert_eq!(terminal, None);
3695 }
3696 other => panic!("unexpected push: {other:?}"),
3697 }
3698 assert!(!serde_json::to_string(&decoded)
3699 .unwrap()
3700 .contains("terminal"));
3701 }
3702
3703 #[test]
3704 fn old_route_closed_decoder_ignores_new_terminal_field() {
3705 #[derive(serde::Deserialize)]
3706 #[serde(tag = "op")]
3707 enum LegacyClientControlPush {
3708 #[serde(rename = "route.closed")]
3709 RouteClosed {
3710 module_id: String,
3711 reason: RouteCloseReason,
3712 drained: bool,
3713 abandoned: u32,
3714 },
3715 }
3716
3717 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3718 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3719 match decoded {
3720 LegacyClientControlPush::RouteClosed {
3721 module_id,
3722 reason,
3723 drained,
3724 abandoned,
3725 } => {
3726 assert_eq!(module_id, "aft-tools");
3727 assert_eq!(reason, RouteCloseReason::Crash);
3728 assert!(!drained);
3729 assert_eq!(abandoned, 0);
3730 }
3731 }
3732 }
3733
3734 #[test]
3735 fn supervisor_routes_is_a_control_plane_request() {
3736 let body = serde_json::json!({
3737 "op": "supervisor.routes",
3738 "module_id": "aft"
3739 });
3740
3741 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3742 assert_eq!(serde_json::to_value(request).unwrap(), body);
3743 }
3744
3745 #[test]
3746 fn diagnostic_string_enums_retain_unknown_wire_values() {
3747 let reason: RunningImageUnavailableReason =
3748 serde_json::from_str("\"future_reason\"").unwrap();
3749 let disposition: TerminalDisposition =
3750 serde_json::from_str("\"future_disposition\"").unwrap();
3751
3752 assert_eq!(
3753 reason,
3754 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3755 );
3756 assert_eq!(
3757 disposition,
3758 TerminalDisposition::Unknown("future_disposition".to_string())
3759 );
3760 }
3761
3762 #[test]
3763 fn diagnostic_string_enums_preserve_existing_wire_names() {
3764 let names = [
3765 (RunningImageUnavailableReason::NotRunning, "not_running"),
3766 (
3767 RunningImageUnavailableReason::UnsupportedPlatform,
3768 "unsupported_platform",
3769 ),
3770 (
3771 RunningImageUnavailableReason::RunningExecutableUnreadable,
3772 "running_executable_unreadable",
3773 ),
3774 (
3775 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3776 "running_executable_permission_denied",
3777 ),
3778 (
3779 RunningImageUnavailableReason::ProcessHidden,
3780 "process_hidden",
3781 ),
3782 (
3783 RunningImageUnavailableReason::SpawnedPathUnreadable,
3784 "spawned_path_unreadable",
3785 ),
3786 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3787 (
3788 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3789 "process_identity_unconfirmed",
3790 ),
3791 ];
3792 for (value, expected) in names {
3793 let wire = serde_json::to_string(&value).unwrap();
3794 assert_eq!(wire, format!("\"{expected}\""));
3795 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3796 assert_eq!(decoded, value);
3797 }
3798
3799 for (value, expected) in [
3800 (TerminalDisposition::Stopped, "stopped"),
3801 (TerminalDisposition::Disabled, "disabled"),
3802 (TerminalDisposition::Failed, "failed"),
3803 (TerminalDisposition::Restarting, "restarting"),
3804 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3805 ] {
3806 let wire = serde_json::to_string(&value).unwrap();
3807 assert_eq!(wire, format!("\"{expected}\""));
3808 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3809 assert_eq!(decoded, value);
3810 }
3811 }
3812
3813 #[test]
3814 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3815 let entry = SupervisorEntry::new(
3816 "waiting-module",
3817 "starting",
3818 true,
3819 false,
3820 SupervisorHealthStatus::Unknown,
3821 );
3822 let old_wire = serde_json::to_value(&entry).unwrap();
3823 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3824 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3825 assert_eq!(decoded.waiting_for_previous_pid, None);
3826 let entry = entry.with_waiting_for_previous_pid(Some(42));
3827 let wire = serde_json::to_value(&entry).unwrap();
3828 assert_eq!(wire["waiting_for_previous_pid"], 42);
3829 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3830 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3831 }
3832
3833 #[test]
3834 fn diagnostic_string_enums_reject_non_string_bodies() {
3835 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3836 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3837 }
3838
3839 #[test]
3840 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3841 let body = serde_json::json!({
3842 "op": "supervisor.provenance",
3843 "daemon": {
3844 "daemon_build": {},
3845 "daemon_observed": {
3846 "running_image": {
3847 "status": "unavailable",
3848 "reason": "not_running"
3849 }
3850 }
3851 },
3852 "modules": [
3853 {
3854 "module_id": "future",
3855 "module_declared": { "status": "unverifiable" },
3856 "daemon_observed": {
3857 "running_image": {
3858 "status": "unavailable",
3859 "reason": "future_reason"
3860 }
3861 }
3862 },
3863 {
3864 "module_id": "healthy-a",
3865 "module_declared": { "status": "unverifiable" },
3866 "daemon_observed": {
3867 "running_image": {
3868 "status": "match",
3869 "evidence": {
3870 "method": "linux_proc_sha256",
3871 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3872 }
3873 }
3874 }
3875 },
3876 {
3877 "module_id": "healthy-b",
3878 "module_declared": { "status": "unverifiable" },
3879 "daemon_observed": {
3880 "running_image": {
3881 "status": "unavailable",
3882 "reason": "unsupported_platform"
3883 }
3884 }
3885 }
3886 ]
3887 });
3888
3889 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3890 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3891 panic!("decoded wrong response variant");
3892 };
3893 assert_eq!(modules.len(), 3);
3894 assert_eq!(modules[0].module_id, "future");
3895 assert_eq!(
3896 modules[0].daemon_observed.running_image,
3897 RunningImageAgreement::Unavailable {
3898 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3899 }
3900 );
3901 assert_eq!(modules[1].module_id, "healthy-a");
3902 assert_eq!(modules[2].module_id, "healthy-b");
3903 }
3904
3905 #[test]
3906 fn tagged_unknown_values_retain_tag_and_body() {
3907 macro_rules! assert_unknown_round_trip {
3908 ($ty:ident, $field:literal, $value:expr) => {
3909 let value = $value;
3910 let wire = serde_json::to_string(&value).unwrap();
3911 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3912 match decoded {
3913 $ty::Unknown { tag, body } => {
3914 assert_eq!(tag, value[$field].as_str().unwrap());
3915 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3916 }
3917 _ => panic!("decoded known variant"),
3918 }
3919 };
3920 }
3921
3922 assert_unknown_round_trip!(
3923 ModuleDeclaredProvenance,
3924 "status",
3925 serde_json::json!({"status": "future", "build": {"version": 7}})
3926 );
3927 assert_unknown_round_trip!(
3928 RunningImageAgreement,
3929 "status",
3930 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3931 );
3932 assert_unknown_round_trip!(
3933 RunningImageEvidence,
3934 "method",
3935 serde_json::json!({"method": "future", "digest": "abc"})
3936 );
3937 assert_unknown_round_trip!(
3938 SupervisorRouteConsumer,
3939 "kind",
3940 serde_json::json!({"kind": "future", "module_id": "m"})
3941 );
3942 assert_unknown_round_trip!(
3943 StderrCaptureState,
3944 "state",
3945 serde_json::json!({"state": "future", "reason": "because"})
3946 );
3947 assert_unknown_round_trip!(
3948 StderrTailEntry,
3949 "kind",
3950 serde_json::json!({"kind": "future", "text": "line"})
3951 );
3952 assert_unknown_round_trip!(
3953 ChildResourceUsage,
3954 "status",
3955 serde_json::json!({"status": "future", "memory_bytes": 1})
3956 );
3957 }
3958
3959 #[test]
3960 fn child_resource_usage_round_trips_both_known_states() {
3961 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3962 memory_bytes: 0,
3963 memory_kind: ChildMemoryKind::ResidentSet,
3964 swap_bytes: Some(0),
3965 cpu_user_ms: 0,
3966 cpu_system_ms: 0,
3967 });
3968 let wire = serde_json::to_value(&measured).unwrap();
3969 assert_eq!(
3970 wire,
3971 serde_json::json!({
3972 "status": "measured",
3973 "memory_bytes": 0,
3974 "memory_kind": "resident_set",
3975 "swap_bytes": 0,
3976 "cpu_user_ms": 0,
3977 "cpu_system_ms": 0
3978 })
3979 );
3980 assert_eq!(
3981 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3982 measured
3983 );
3984
3985 let unavailable = ChildResourceUsage::Unavailable {
3986 reason: ChildResourceUnavailableReason::NotRunning,
3987 };
3988 let wire = serde_json::to_value(&unavailable).unwrap();
3989 assert_eq!(
3990 wire,
3991 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3992 );
3993 assert_eq!(
3994 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3995 unavailable
3996 );
3997 }
3998
3999 #[test]
4000 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
4001 let stamped: StderrTailEntry = serde_json::from_str(
4005 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
4006 )
4007 .unwrap();
4008 assert_eq!(
4009 stamped,
4010 StderrTailEntry::Line {
4011 text: "boom".to_string(),
4012 truncated: true,
4013 at_ms: Some(1_789_801_440_685),
4014 }
4015 );
4016 let unstamped: StderrTailEntry =
4017 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
4018 assert_eq!(
4019 unstamped,
4020 StderrTailEntry::Line {
4021 text: "boom".to_string(),
4022 truncated: false,
4023 at_ms: None,
4024 }
4025 );
4026 assert_eq!(
4029 serde_json::to_string(&unstamped).unwrap(),
4030 r#"{"kind":"line","text":"boom"}"#
4031 );
4032 assert_eq!(
4033 serde_json::to_value(&stamped).unwrap()["at_ms"],
4034 serde_json::json!(1_789_801_440_685u64)
4035 );
4036 }
4037
4038 #[test]
4039 fn tagged_unknown_values_round_trip_the_original_json() {
4040 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
4041 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4042 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4043 }
4044
4045 #[test]
4046 fn tagged_unknown_values_round_trip_trailing_tag() {
4047 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
4048 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4049 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4050
4051 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
4052 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4053 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4054 }
4055
4056 #[test]
4057 fn tagged_unknown_values_round_trip_middle_tag() {
4058 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
4059 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4060 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4061
4062 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
4063 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4064 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4065 }
4066
4067 #[test]
4068 fn tagged_unknown_values_round_trip_deep_payload() {
4069 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
4070 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4071 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4072
4073 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
4074 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4075 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4076 }
4077
4078 #[test]
4079 fn tagged_unknown_values_reject_non_object_bodies() {
4080 for wire in ["42", r#""future""#, "[]"] {
4081 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
4082 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
4083 }
4084 }
4085
4086 #[test]
4087 fn duplicate_discriminators_reject_without_panicking() {
4088 assert_eq!(
4089 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
4090 .unwrap(),
4091 ModuleDeclaredProvenance::Unverifiable
4092 );
4093 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
4094 .unwrap()
4095 {
4096 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
4097 _ => panic!("future discriminator decoded as a known variant"),
4098 }
4099
4100 let wires = [
4101 r#"{"status":"reported","status":"unverifiable"}"#,
4102 r#"{"status":"unverifiable","status":"reported"}"#,
4103 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4104 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4105 ];
4106
4107 for wire in wires {
4108 let result =
4109 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4110 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4111 assert!(
4112 result.unwrap().is_err(),
4113 "duplicate discriminator decoded: {wire}"
4114 );
4115 }
4116
4117 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4118 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4119 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4120 assert!(
4121 result.unwrap().is_err(),
4122 "duplicate discriminator decoded: {wire}"
4123 );
4124 }
4125
4126 #[test]
4127 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4128 let known_wire =
4129 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4130 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4131 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4132
4133 for wire in [
4134 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4135 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4136 ] {
4137 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4138 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4139 }
4140
4141 for wire in [
4142 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4143 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4144 ] {
4145 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4146 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4147 }
4148
4149 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4150 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4151 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4152
4153 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4154 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4155 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4156 }
4157
4158 #[test]
4159 fn tagged_unknown_member_does_not_discard_known_siblings() {
4160 let body = serde_json::json!({
4161 "modules": [{
4162 "module_id": "target",
4163 "routes": [
4164 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4165 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4166 ]
4167 }]
4168 });
4169 let decoded: ClientControlResponse = serde_json::from_value(
4170 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4171 )
4172 .unwrap();
4173 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4174 panic!("decoded wrong response variant");
4175 };
4176 assert_eq!(modules[0].routes.len(), 2);
4177 assert_eq!(
4178 modules[0].routes[1].consumer,
4179 SupervisorRouteConsumer::Direct { connection_id: 7 }
4180 );
4181 }
4182}
4183
4184#[cfg(test)]
4185mod launch_nonce_redaction_tests {
4186 use super::*;
4187
4188 const NONCE: &str = "nonce-f00dfeed1234abcd";
4189
4190 fn identity() -> ConsumerIdentity {
4191 ConsumerIdentity {
4192 module_id: "wernicke".to_string(),
4193 launch_nonce: NONCE.to_string(),
4194 }
4195 }
4196
4197 #[test]
4198 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4199 let printed = format!("{:?}", identity());
4200 assert!(printed.contains("wernicke"), "{printed}");
4201 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4202 }
4203
4204 #[test]
4205 fn route_open_request_debug_never_prints_the_nonce() {
4206 let request = ClientControlRequest::RouteOpen {
4207 busy_refusals: None,
4208 target: subc_protocol::RouteTarget::ToolProvider {
4209 module_id: "broca".to_string(),
4210 },
4211 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4212 consumer_identity: Some(identity()),
4213 consumer_capabilities: None,
4214 role_versions: None,
4215 admission_facts: None,
4216 scope: None,
4217 };
4218 let printed = format!("{request:?}");
4219 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4220 }
4221}
4222
4223#[cfg(test)]
4224mod reader_skew_tests {
4225 use super::*;
4226 use serde_json::{json, Value};
4227
4228 fn catalog() -> Value {
4229 json!({"module_id": "provider", "roles": [], "control_ops": []})
4230 }
4231
4232 fn reply() -> Value {
4233 json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4234 }
4235
4236 fn target() -> Value {
4237 json!({
4238 "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4239 "authority_epoch": 23, "first_party": true,
4240 "approved_declarations_digest": "approved"
4241 })
4242 }
4243
4244 fn request() -> Value {
4245 json!({
4246 "op": "route.open",
4247 "target": {"kind": "tool_provider", "module_id": "provider"},
4248 "identity": {"harness": "test", "session": "session-1"}
4249 })
4250 }
4251
4252 #[test]
4253 fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4254 let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4255 let built = CatalogEntry::new("provider", vec![], vec![]);
4256 assert_eq!(old, built);
4257 assert_eq!(old.first_party, None);
4258 let old_bytes = serde_json::to_value(&old).unwrap();
4259 let additions = json!({
4260 "incarnation": "daemon", "spawn": 17, "first_party": false,
4261 "origin": "development", "requested_declarations_digest": "requested",
4262 "approved_declarations_digest": "approved"
4263 });
4264 let mut body = catalog();
4265 for (key, value) in additions.as_object().unwrap() {
4266 assert!(old_bytes.get(key).is_none(), "{key}");
4267 body[key] = value.clone();
4268 }
4269 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4270 let encoded = serde_json::to_value(&decoded).unwrap();
4271 for (key, value) in additions.as_object().unwrap() {
4272 assert_eq!(&encoded[key], value, "{key}");
4273 }
4274 assert_eq!(decoded.first_party, Some(false));
4275 assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4276 }
4277
4278 #[test]
4279 fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4280 let mut body = catalog();
4281 body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4282 body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4283 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4284 let encoded = serde_json::to_value(decoded).unwrap();
4285 for key in ["requested_declarations", "approved_declarations"] {
4286 assert_eq!(encoded[key], body[key]);
4287 }
4288 let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4289 assert_eq!(unfiltered.approved_declarations, None);
4290 assert_eq!(unfiltered.requested_declarations, None);
4291 }
4292
4293 #[test]
4294 fn reader_skew_catalog_unknown_origin_is_other() {
4295 let mut body = catalog();
4296 body["origin"] = json!("future-origin");
4297 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4298 assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4299 }
4300
4301 #[test]
4302 fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4303 let mut body = catalog();
4304 body["spawn"] = json!(9_007_199_254_740_991_u64);
4305 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4306 assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4307 for invalid in [
4308 json!(9_007_199_254_740_992_u64),
4309 json!(-1),
4310 json!(1.5),
4311 json!("17"),
4312 ] {
4313 body["spawn"] = invalid;
4314 assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4315 }
4316 }
4317
4318 #[test]
4319 fn reader_skew_catalog_watch_request_uses_subscription_op() {
4320 let body = json!({"op": "catalog.watch"});
4321 let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4322 assert_eq!(request, CatalogWatchRequest::new());
4323 assert_eq!(serde_json::to_value(request).unwrap(), body);
4324 assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4325 for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4326 assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4327 }
4328 }
4329
4330 #[test]
4331 fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4332 for generation in [0, 19, 42] {
4333 let body = json!({"op": "catalog.watch", "generation": generation});
4334 let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4335 assert_eq!(push, CatalogWatchResponse::new(generation));
4336 assert_eq!(serde_json::to_value(push).unwrap(), body);
4337 }
4338 assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4339 for invalid in [
4340 json!({"op": "catalog.watch"}),
4341 json!({"op": "activity.subscribe", "generation": 1}),
4342 ] {
4343 assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4344 }
4345 }
4346
4347 #[test]
4348 fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4349 let mut body = reply();
4350 let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4351 let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4352 assert_eq!(empty, RouteOpenReplyExt::new());
4353 empty.write_to(&mut body).unwrap();
4354 assert_eq!(body, reply());
4355 body["target"] = target();
4356 let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4357 assert_eq!(
4358 decoded.target.as_ref().unwrap().kind,
4359 RouteOpenTargetKind::Spawn
4360 );
4361 let mut encoded = reply();
4362 RouteOpenReplyExt::new()
4363 .with_target(decoded.target)
4364 .write_to(&mut encoded)
4365 .unwrap();
4366 assert_eq!(encoded, body);
4367 assert_eq!(
4368 serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4369 legacy
4370 );
4371 RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4372 assert_eq!(encoded, reply());
4373 }
4374
4375 #[test]
4376 fn reader_skew_route_open_incomplete_target_is_unmarked() {
4377 let mut body = reply();
4378 body["target"] = target();
4379 assert!(RouteOpenReplyExt::read_from(&body)
4380 .unwrap()
4381 .target
4382 .is_some());
4383 for key in [
4384 "incarnation",
4385 "kind",
4386 "spawn",
4387 "authority_epoch",
4388 "first_party",
4389 "approved_declarations_digest",
4390 ] {
4391 let mut incomplete = body.clone();
4392 incomplete["target"].as_object_mut().unwrap().remove(key);
4393 assert_eq!(
4394 RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4395 None,
4396 "{key}"
4397 );
4398 }
4399 body["target"] = Value::Null;
4400 assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4401 }
4402
4403 #[test]
4404 fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4405 for (kind, expected) in [
4406 ("prefix", RouteOpenTargetKind::Prefix),
4407 ("unsupervised", RouteOpenTargetKind::Unsupervised),
4408 ] {
4409 let mut body = reply();
4410 body["target"] = target();
4411 body["target"]["kind"] = json!(kind);
4412 body["target"]["spawn"] = json!("not-a-spawn");
4414 body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4415 body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4416 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4417 let target = ext.target.as_ref().unwrap();
4418 assert_eq!(target.kind, expected);
4419 assert_eq!(target.spawn, None);
4420 assert_eq!(target.authority_epoch, None);
4421 assert_eq!(target.approved_declarations_digest, None);
4422 assert!(!target.first_party);
4423 let mut encoded = reply();
4424 ext.write_to(&mut encoded).unwrap();
4425 for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
4426 assert!(encoded["target"].get(key).is_none());
4427 }
4428 }
4429 }
4430
4431 #[test]
4432 fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4433 let mut body = reply();
4434 body["target"] = target();
4435 body["target"]["kind"] = json!("future-kind");
4436 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4437 let target = ext.target.unwrap();
4438 assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4439 assert_eq!(target.spawn, None);
4440 assert_eq!(target.authority_epoch, None);
4441 assert_eq!(target.approved_declarations_digest, None);
4442 assert!(!target.first_party);
4443 }
4444
4445 #[test]
4446 fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4447 for field in ["spawn", "authority_epoch"] {
4448 let mut body = reply();
4449 body["target"] = target();
4450 body["target"][field] = json!(9_007_199_254_740_991_u64);
4451 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4452 assert_eq!(
4453 serde_json::to_value(ext).unwrap()["target"][field],
4454 9_007_199_254_740_991_u64
4455 );
4456 for invalid in [
4457 json!(9_007_199_254_740_992_u64),
4458 json!(-1),
4459 json!(1.5),
4460 json!("17"),
4461 ] {
4462 body["target"][field] = invalid;
4463 assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4464 let mut incomplete = body.clone();
4465 incomplete["target"]
4466 .as_object_mut()
4467 .unwrap()
4468 .remove("incarnation");
4469 assert!(
4470 RouteOpenReplyExt::read_from(&incomplete).is_err(),
4471 "{field}"
4472 );
4473 }
4474 }
4475 }
4476
4477 #[test]
4478 fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4479 let mut body = request();
4480 let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4481 assert_eq!(
4482 RouteOpenRequestExt::read_from(&body).unwrap(),
4483 RouteOpenRequestExt::new()
4484 );
4485 RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4486 assert_eq!(body, request());
4487 body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4488 let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4489 assert_eq!(
4490 decoded.accepts_close_reasons,
4491 Some(vec!["authority_changed".into(), "future-reason".into()])
4492 );
4493 let mut encoded = request();
4494 RouteOpenRequestExt::new()
4495 .with_accepts_close_reasons(decoded.accepts_close_reasons)
4496 .write_to(&mut encoded)
4497 .unwrap();
4498 assert_eq!(encoded, body);
4499 assert_eq!(
4500 serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4501 legacy
4502 );
4503 RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4504 assert_eq!(encoded, request());
4505 assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4506 }
4507
4508 #[test]
4509 fn reader_skew_route_open_helpers_refuse_other_bodies() {
4510 for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4511 assert!(RouteOpenRequestExt::read_from(&body).is_err());
4512 assert!(RouteOpenReplyExt::read_from(&body).is_err());
4513 assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4514 assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4515 }
4516 }
4517
4518 #[test]
4519 fn reader_skew_route_open_target_constructor_validates_like_reader() {
4520 let spawn = RouteOpenTarget::new(
4521 "daemon",
4522 RouteOpenTargetKind::Spawn,
4523 Some(17),
4524 Some(23),
4525 true,
4526 Some("approved".into()),
4527 )
4528 .unwrap();
4529 assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4530 for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4531 assert!(RouteOpenTarget::new(
4532 "daemon",
4533 RouteOpenTargetKind::Spawn,
4534 Some(spawn),
4535 Some(epoch),
4536 true,
4537 Some("approved".into())
4538 )
4539 .is_err());
4540 }
4541 }
4542}
4543
4544#[cfg(test)]
4545mod claim_wire_tests {
4546 use super::*;
4547 use serde_json::{json, Value};
4548
4549 fn legacy_provenance() -> SupervisorModuleProvenance {
4550 SupervisorModuleProvenance {
4551 module_id: "worker".into(),
4552 module_declared: ModuleDeclaredProvenance::Unverifiable,
4553 daemon_observed: SupervisorObservedProcess {
4554 launch_nonce_source: None,
4555 pid: None,
4556 spawned_at_ms: None,
4557 spawned_from: None,
4558 running_image: RunningImageAgreement::Unavailable {
4559 reason: RunningImageUnavailableReason::NotRunning,
4560 },
4561 },
4562 }
4563 }
4564
4565 #[test]
4566 fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4567 let legacy = legacy_provenance();
4568 let original = serde_json::to_value(&legacy).unwrap();
4569 let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4570 assert_eq!(absent.registration, None);
4571 let mut wire = original.clone();
4572 absent.write_to(&mut wire).unwrap();
4573 assert_eq!(wire, original);
4574 for (method, spelling) in [
4575 (RegistrationMethod::Channel, "channel"),
4576 (RegistrationMethod::Nonce, "nonce"),
4577 ] {
4578 let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4579 ext.write_to(&mut wire).unwrap();
4580 assert_eq!(wire["registration"], spelling);
4581 assert_eq!(
4582 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4583 ext
4584 );
4585 let old_reader: SupervisorModuleProvenance =
4586 serde_json::from_value(wire.clone()).unwrap();
4587 assert_eq!(old_reader, legacy);
4588 assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4589 }
4590 absent.write_to(&mut wire).unwrap();
4591 assert_eq!(wire, original);
4592 for mut invalid in [Value::Null, json!([]), json!("entry")] {
4593 assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4594 assert!(absent.write_to(&mut invalid).is_err());
4595 }
4596 }
4597
4598 #[test]
4599 fn provenance_unknown_registration_is_not_channel_or_nonce() {
4600 let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4601 wire["registration"] = json!("future_method");
4602 let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4603 assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4604 assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4605 assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4606 wire["registration"] = json!(false);
4607 assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4608 }
4609
4610 #[test]
4611 fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4612 let original = serde_json::to_value(legacy_provenance()).unwrap();
4613 for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4614 let mut golden = original.clone();
4615 golden["registration_declaration"] = json!(declaration);
4616 let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4617 assert_eq!(
4618 serde_json::to_value(&extension).unwrap(),
4619 json!({
4620 "registration_declaration": declaration
4621 })
4622 );
4623 let mut written = original.clone();
4624 extension.write_to(&mut written).unwrap();
4625 assert_eq!(written, golden);
4626 assert_eq!(
4627 serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4628 legacy_provenance()
4629 );
4630 SupervisorModuleProvenanceExt::new()
4631 .write_to(&mut written)
4632 .unwrap();
4633 assert_eq!(written, original);
4634 }
4635 }
4636
4637 #[test]
4638 fn admission_refusal_is_optional_and_open() {
4639 let entry = SupervisorEntry::new(
4640 "worker",
4641 "stopped",
4642 true,
4643 false,
4644 SupervisorHealthStatus::Unknown,
4645 );
4646 let original = serde_json::to_value(&entry).unwrap();
4647 assert!(original.get("admission_refused").is_none());
4648 let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
4649 assert_eq!(read.admission_refused, None);
4650 assert_eq!(serde_json::to_value(read).unwrap(), original);
4651 assert_eq!(
4652 REGISTRATION_CHANNEL_UNSUPPORTED,
4653 "registration_channel_unsupported"
4654 );
4655 for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
4656 let mut wire = original.clone();
4657 wire["admission_refused"] = json!(reason);
4658 let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
4659 assert_eq!(read.admission_refused.as_deref(), Some(reason));
4660 assert_eq!(serde_json::to_value(read).unwrap(), wire);
4661 let built = entry.clone().with_admission_refused(Some(reason.into()));
4662 assert_eq!(serde_json::to_value(built).unwrap(), wire);
4663 }
4664 }
4665}