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