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