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}
1018
1019#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1021pub struct SupervisorModuleProvenance {
1022 pub module_id: String,
1023 pub module_declared: ModuleDeclaredProvenance,
1024 pub daemon_observed: SupervisorObservedProcess,
1025}
1026
1027#[non_exhaustive]
1030#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1031pub struct SupervisorModuleProvenanceExt {
1032 #[serde(default, skip_serializing_if = "Option::is_none")]
1034 pub registration: Option<RegistrationMethod>,
1035 #[serde(default, skip_serializing_if = "Option::is_none")]
1039 pub registration_declaration: Option<String>,
1040}
1041
1042impl SupervisorModuleProvenanceExt {
1043 pub fn new() -> Self {
1044 Self::default()
1045 }
1046
1047 #[must_use]
1048 pub fn with_registration(mut self, registration: Option<RegistrationMethod>) -> Self {
1049 self.registration = registration;
1050 self
1051 }
1052
1053 pub fn read_from(entry: &serde_json::Value) -> serde_json::Result<Self> {
1055 if !entry.is_object() {
1056 return Err(serde_json::Error::custom(
1057 "expected a module provenance entry object",
1058 ));
1059 }
1060 serde_json::from_value(entry.clone())
1061 }
1062
1063 pub fn write_to(&self, entry: &mut serde_json::Value) -> serde_json::Result<()> {
1066 let object = entry.as_object_mut().ok_or_else(|| {
1067 serde_json::Error::custom("expected a module provenance entry object")
1068 })?;
1069 object.remove("registration");
1070 if let Some(method) = &self.registration {
1071 object.insert("registration".into(), serde_json::to_value(method)?);
1072 }
1073 object.remove("registration_declaration");
1074 if let Some(declaration) = &self.registration_declaration {
1075 object.insert(
1076 "registration_declaration".into(),
1077 declaration.clone().into(),
1078 );
1079 }
1080 Ok(())
1081 }
1082}
1083
1084#[non_exhaustive]
1087#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1088#[serde(rename_all = "snake_case")]
1089pub enum RegistrationMethod {
1090 Channel,
1091 Nonce,
1092 #[serde(other)]
1093 Unknown,
1094}
1095
1096pub const REGISTRATION_CHANNEL_UNSUPPORTED: &str = "registration_channel_unsupported";
1099
1100#[derive(Debug, Clone, PartialEq)]
1102pub enum ModuleDeclaredProvenance {
1103 Reported {
1104 build: ManifestProvenance,
1105 },
1106 Unverifiable,
1107 Unknown {
1110 tag: String,
1111 body: OrderedJsonObject,
1112 },
1113}
1114
1115#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1120pub struct SupervisorObservedProcess {
1121 #[serde(default, skip_serializing_if = "Option::is_none")]
1127 pub launch_nonce_source: Option<String>,
1128 #[serde(default, skip_serializing_if = "Option::is_none")]
1129 pub pid: Option<u32>,
1130 #[serde(default, skip_serializing_if = "Option::is_none")]
1131 pub spawned_at_ms: Option<u64>,
1132 #[serde(default, skip_serializing_if = "Option::is_none")]
1133 pub spawned_from: Option<PathBuf>,
1134 pub running_image: RunningImageAgreement,
1135}
1136
1137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1154#[non_exhaustive]
1155pub struct PendingReloadVerdict {
1156 pub path: ReloadPathAgreement,
1157 pub image: RunningImageAgreement,
1158 #[serde(default, skip_serializing_if = "Option::is_none")]
1159 pub spec: Option<LaunchSpecAgreement>,
1160}
1161
1162impl PendingReloadVerdict {
1163 #[must_use]
1165 pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
1166 Self {
1167 path,
1168 image,
1169 spec: None,
1170 }
1171 }
1172
1173 #[must_use]
1175 pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
1176 self.spec = spec;
1177 self
1178 }
1179}
1180
1181#[cfg(test)]
1182mod launch_spec_wire_tests {
1183 use super::*;
1184
1185 #[test]
1186 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
1187 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
1188 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
1189 assert_eq!(parsed.spec, None);
1190 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
1191 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
1192 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
1193 assert!(
1194 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
1195 );
1196 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
1197 let unavailable = LaunchSpecAgreement::Unavailable {
1198 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
1199 };
1200 let encoded = serde_json::to_string(&unavailable).unwrap();
1201 assert_eq!(
1202 encoded,
1203 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
1204 );
1205 assert_eq!(
1206 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
1207 unavailable
1208 );
1209 }
1210}
1211
1212#[derive(Debug, Clone, PartialEq)]
1215pub enum LaunchSpecAgreement {
1216 Match,
1217 Mismatch,
1218 Unavailable {
1219 reason: LaunchSpecUnavailableReason,
1220 },
1221 Unknown {
1222 tag: String,
1223 body: OrderedJsonObject,
1224 },
1225}
1226
1227open_string_enum! {
1228 LaunchSpecUnavailableReason {
1229 NotRunning => "not_running",
1230 SpawnedSpecUnavailable => "spawned_spec_unavailable",
1231 }
1232}
1233
1234#[derive(Debug, Clone, PartialEq)]
1236pub enum ReloadPathAgreement {
1237 Match,
1238 Mismatch {
1239 configured: PathBuf,
1240 spawned_from: PathBuf,
1241 },
1242 Unavailable {
1243 reason: ReloadPathUnavailableReason,
1244 },
1245 Unknown {
1246 tag: String,
1247 body: OrderedJsonObject,
1248 },
1249}
1250
1251open_string_enum! {
1252 ReloadPathUnavailableReason {
1254 NotRunning => "not_running",
1255 SpawnedPathUnavailable => "spawned_path_unavailable",
1256 }
1257}
1258
1259#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1261pub struct SupervisorDaemonProvenance {
1262 pub daemon_build: DaemonBuildProvenance,
1263 pub daemon_observed: DaemonObservedProcess,
1264}
1265
1266#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1268pub struct DaemonBuildProvenance {
1269 #[serde(default, skip_serializing_if = "Option::is_none")]
1270 pub build_git_sha: Option<String>,
1271 #[serde(default, skip_serializing_if = "Option::is_none")]
1272 pub build_lock_digest: Option<String>,
1273}
1274
1275#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1277pub struct DaemonObservedProcess {
1278 #[serde(default, skip_serializing_if = "Option::is_none")]
1279 pub pid: Option<u32>,
1280 #[serde(default, skip_serializing_if = "Option::is_none")]
1285 pub started_at_ms: Option<u64>,
1286 pub running_image: RunningImageAgreement,
1287}
1288
1289#[derive(Debug, Clone, PartialEq)]
1291pub enum RunningImageAgreement {
1292 Match {
1293 evidence: RunningImageEvidence,
1294 },
1295 Mismatch {
1296 running: RunningImageEvidence,
1297 disk: RunningImageEvidence,
1298 },
1299 Unavailable {
1300 reason: RunningImageUnavailableReason,
1301 },
1302 Unknown {
1305 tag: String,
1306 body: OrderedJsonObject,
1307 },
1308}
1309
1310#[derive(Debug, Clone, PartialEq)]
1312pub enum RunningImageEvidence {
1313 LinuxProcSha256 {
1314 digest: String,
1315 },
1316 MacosSpawnInode {
1317 device: u64,
1318 inode: u64,
1319 },
1320 WindowsSpawnFileId {
1322 volume_serial_number: u64,
1323 file_id: [u8; 16],
1324 },
1325 Unknown {
1328 tag: String,
1329 body: OrderedJsonObject,
1330 },
1331}
1332
1333open_string_enum! {
1334 RunningImageUnavailableReason {
1336 NotRunning => "not_running",
1337 NotYetMeasured => "not_yet_measured",
1338 UnsupportedPlatform => "unsupported_platform",
1339 RunningExecutableUnreadable => "running_executable_unreadable",
1340 RunningExecutablePermissionDenied => "running_executable_permission_denied",
1341 ProcessHidden => "process_hidden",
1342 SpawnedPathUnreadable => "spawned_path_unreadable",
1343 HashFailed => "hash_failed",
1344 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
1345 }
1346}
1347
1348#[derive(Debug, Clone, PartialEq)]
1354pub enum SupervisorRouteConsumer {
1355 Reserved {
1356 module_id: String,
1357 },
1358 Direct {
1359 connection_id: u64,
1360 },
1361 Unknown {
1364 tag: String,
1365 body: OrderedJsonObject,
1366 },
1367}
1368
1369#[derive(Debug, Clone, PartialEq)]
1376pub enum StderrCaptureState {
1377 Captured,
1380 Incomplete { reason: String },
1382 NotCaptured { reason: String },
1384 Unknown {
1387 tag: String,
1388 body: OrderedJsonObject,
1389 },
1390}
1391
1392#[derive(Debug, Clone, PartialEq)]
1393pub enum StderrTailEntry {
1394 Line {
1395 text: String,
1396 truncated: bool,
1401 at_ms: Option<u64>,
1405 },
1406 ProcessStart,
1411 Unknown {
1414 tag: String,
1415 body: OrderedJsonObject,
1416 },
1417}
1418
1419#[derive(Debug, Serialize, Deserialize)]
1420#[serde(tag = "status", rename_all = "snake_case")]
1421enum ModuleDeclaredProvenanceWire {
1422 Reported { build: ManifestProvenance },
1423 Unverifiable,
1424}
1425
1426#[derive(Debug, Serialize, Deserialize)]
1427#[serde(tag = "status", rename_all = "snake_case")]
1428enum RunningImageAgreementWire {
1429 Match {
1430 evidence: RunningImageEvidence,
1431 },
1432 Mismatch {
1433 running: RunningImageEvidence,
1434 disk: RunningImageEvidence,
1435 },
1436 Unavailable {
1437 reason: RunningImageUnavailableReason,
1438 },
1439}
1440
1441#[derive(Debug, Serialize, Deserialize)]
1442#[serde(tag = "status", rename_all = "snake_case")]
1443enum ReloadPathAgreementWire {
1444 Match,
1445 Mismatch {
1446 configured: PathBuf,
1447 spawned_from: PathBuf,
1448 },
1449 Unavailable {
1450 reason: ReloadPathUnavailableReason,
1451 },
1452}
1453
1454#[derive(Debug, Serialize, Deserialize)]
1455#[serde(tag = "status", rename_all = "snake_case")]
1456enum LaunchSpecAgreementWire {
1457 Match,
1458 Mismatch,
1459 Unavailable { reason: LaunchSpecUnavailableReason },
1460}
1461
1462#[derive(Debug, Serialize, Deserialize)]
1463#[serde(tag = "method", rename_all = "snake_case")]
1464enum RunningImageEvidenceWire {
1465 LinuxProcSha256 {
1466 digest: String,
1467 },
1468 MacosSpawnInode {
1469 device: u64,
1470 inode: u64,
1471 },
1472 WindowsSpawnFileId {
1473 volume_serial_number: u64,
1474 file_id: [u8; 16],
1475 },
1476}
1477
1478#[derive(Debug, Serialize, Deserialize)]
1479#[serde(tag = "kind", rename_all = "snake_case")]
1480enum SupervisorRouteConsumerWire {
1481 Reserved { module_id: String },
1482 Direct { connection_id: u64 },
1483}
1484
1485#[derive(Debug, Serialize, Deserialize)]
1486#[serde(tag = "state", rename_all = "snake_case")]
1487enum StderrCaptureStateWire {
1488 Captured,
1489 Incomplete { reason: String },
1490 NotCaptured { reason: String },
1491}
1492
1493#[derive(Debug, Serialize, Deserialize)]
1494#[serde(tag = "status", rename_all = "snake_case")]
1495enum ChildResourceUsageWire {
1496 Measured(ChildResourceReading),
1497 Unavailable {
1498 reason: ChildResourceUnavailableReason,
1499 },
1500}
1501
1502#[derive(Debug, Serialize, Deserialize)]
1503#[serde(tag = "kind", rename_all = "snake_case")]
1504enum StderrTailEntryWire {
1505 Line {
1506 text: String,
1507 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1508 truncated: bool,
1509 #[serde(default, skip_serializing_if = "Option::is_none")]
1512 at_ms: Option<u64>,
1513 },
1514 ProcessStart,
1515}
1516
1517#[derive(Debug, Clone, PartialEq)]
1519pub enum OrderedJsonValue {
1520 Null,
1521 Bool(bool),
1522 Number(serde_json::Number),
1523 String(String),
1524 Array(Vec<Self>),
1525 Object(OrderedJsonObject),
1526}
1527
1528#[derive(Debug, Clone, PartialEq)]
1530pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1531
1532impl OrderedJsonObject {
1533 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1535 &self.0
1536 }
1537
1538 fn into_value(self) -> serde_json::Value {
1539 serde_json::Value::Object(
1540 self.0
1541 .into_iter()
1542 .map(|(key, value)| (key, value.into_value()))
1543 .collect(),
1544 )
1545 }
1546}
1547
1548impl OrderedJsonValue {
1549 fn into_value(self) -> serde_json::Value {
1550 match self {
1551 Self::Null => serde_json::Value::Null,
1552 Self::Bool(value) => serde_json::Value::Bool(value),
1553 Self::Number(value) => serde_json::Value::Number(value),
1554 Self::String(value) => serde_json::Value::String(value),
1555 Self::Array(values) => {
1556 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1557 }
1558 Self::Object(value) => value.into_value(),
1559 }
1560 }
1561}
1562
1563impl Serialize for OrderedJsonValue {
1564 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1565 where
1566 S: Serializer,
1567 {
1568 match self {
1569 Self::Null => serializer.serialize_unit(),
1570 Self::Bool(value) => serializer.serialize_bool(*value),
1571 Self::Number(value) => value.serialize(serializer),
1572 Self::String(value) => serializer.serialize_str(value),
1573 Self::Array(values) => values.serialize(serializer),
1574 Self::Object(value) => value.serialize(serializer),
1575 }
1576 }
1577}
1578
1579impl<'de> Deserialize<'de> for OrderedJsonValue {
1580 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1581 where
1582 D: Deserializer<'de>,
1583 {
1584 struct OrderedValueVisitor;
1585
1586 impl<'de> Visitor<'de> for OrderedValueVisitor {
1587 type Value = OrderedJsonValue;
1588
1589 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1590 formatter.write_str("a JSON value with ordered object members")
1591 }
1592
1593 fn visit_unit<E>(self) -> Result<Self::Value, E>
1594 where
1595 E: serde::de::Error,
1596 {
1597 Ok(OrderedJsonValue::Null)
1598 }
1599
1600 fn visit_none<E>(self) -> Result<Self::Value, E>
1601 where
1602 E: serde::de::Error,
1603 {
1604 Ok(OrderedJsonValue::Null)
1605 }
1606
1607 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1608 where
1609 D: Deserializer<'de>,
1610 {
1611 OrderedJsonValue::deserialize(deserializer)
1612 }
1613
1614 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1615 where
1616 E: serde::de::Error,
1617 {
1618 Ok(OrderedJsonValue::Bool(value))
1619 }
1620
1621 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1622 where
1623 E: serde::de::Error,
1624 {
1625 Ok(OrderedJsonValue::Number(value.into()))
1626 }
1627
1628 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1629 where
1630 E: serde::de::Error,
1631 {
1632 Ok(OrderedJsonValue::Number(value.into()))
1633 }
1634
1635 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1636 where
1637 E: serde::de::Error,
1638 {
1639 serde_json::Number::from_f64(value)
1640 .map(OrderedJsonValue::Number)
1641 .ok_or_else(|| E::custom("non-finite JSON number"))
1642 }
1643
1644 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1645 where
1646 E: serde::de::Error,
1647 {
1648 Ok(OrderedJsonValue::String(value.to_owned()))
1649 }
1650
1651 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1652 where
1653 E: serde::de::Error,
1654 {
1655 Ok(OrderedJsonValue::String(value))
1656 }
1657
1658 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1659 where
1660 A: SeqAccess<'de>,
1661 {
1662 let mut values = Vec::new();
1663 while let Some(value) = sequence.next_element()? {
1664 values.push(value);
1665 }
1666 Ok(OrderedJsonValue::Array(values))
1667 }
1668
1669 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1670 where
1671 A: MapAccess<'de>,
1672 {
1673 let mut entries = Vec::new();
1674 while let Some((key, value)) = map.next_entry()? {
1675 entries.push((key, value));
1676 }
1677 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1678 }
1679 }
1680
1681 deserializer.deserialize_any(OrderedValueVisitor)
1682 }
1683}
1684
1685impl Serialize for OrderedJsonObject {
1686 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1687 where
1688 S: Serializer,
1689 {
1690 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1691 for (key, value) in &self.0 {
1692 map.serialize_entry(key, value)?;
1693 }
1694 map.end()
1695 }
1696}
1697
1698impl<'de> Deserialize<'de> for OrderedJsonObject {
1699 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1700 where
1701 D: Deserializer<'de>,
1702 {
1703 struct OrderedObjectVisitor;
1704
1705 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1706 type Value = OrderedJsonObject;
1707
1708 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1709 formatter.write_str("an object with ordered JSON members")
1710 }
1711
1712 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1713 where
1714 A: MapAccess<'de>,
1715 {
1716 let mut entries = Vec::new();
1717 while let Some((key, value)) = map.next_entry()? {
1718 entries.push((key, value));
1719 }
1720 Ok(OrderedJsonObject(entries))
1721 }
1722 }
1723
1724 deserializer.deserialize_map(OrderedObjectVisitor)
1725 }
1726}
1727
1728fn read_tagged<'de, D>(
1729 deserializer: D,
1730 field: &'static str,
1731) -> Result<(String, OrderedJsonObject), D::Error>
1732where
1733 D: Deserializer<'de>,
1734{
1735 let body = OrderedJsonObject::deserialize(deserializer)?;
1736 let mut tag = None;
1737 for (key, value) in body.as_entries() {
1738 if key != field {
1739 continue;
1740 }
1741 if tag.is_some() {
1742 return Err(D::Error::custom(format!(
1743 "tagged object has duplicate `{field}` field"
1744 )));
1745 }
1746 let OrderedJsonValue::String(value) = value else {
1747 return Err(D::Error::custom(format!(
1748 "tagged object has no string `{field}` field"
1749 )));
1750 };
1751 tag = Some(value);
1752 }
1753 let Some(tag) = tag else {
1754 return Err(D::Error::custom(format!(
1755 "tagged object has no string `{field}` field"
1756 )));
1757 };
1758 Ok((tag.to_string(), body))
1759}
1760
1761fn read_ordered_tagged(
1762 value: OrderedJsonValue,
1763 field: &'static str,
1764) -> Result<(String, OrderedJsonObject), String> {
1765 let OrderedJsonValue::Object(body) = value else {
1766 return Err(format!("expected tagged object with `{field}` field"));
1767 };
1768 let mut tag = None;
1769 for (key, value) in body.as_entries() {
1770 if key != field {
1771 continue;
1772 }
1773 if tag.is_some() {
1774 return Err(format!("tagged object has duplicate `{field}` field"));
1775 }
1776 let OrderedJsonValue::String(value) = value else {
1777 return Err(format!("tagged object has no string `{field}` field"));
1778 };
1779 tag = Some(value);
1780 }
1781 let Some(tag) = tag else {
1782 return Err(format!("tagged object has no string `{field}` field"));
1783 };
1784 Ok((tag.to_string(), body))
1785}
1786
1787fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1788 body.as_entries()
1789 .iter()
1790 .find_map(|(key, value)| (key == field).then_some(value))
1791}
1792
1793fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1794 match ordered_field(body, field) {
1795 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1796 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1797 None => Err(format!("tagged object has no `{field}` field")),
1798 }
1799}
1800
1801fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1802 let (tag, body) = read_ordered_tagged(value, "method")?;
1803 match tag.as_str() {
1804 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1805 digest: ordered_string(&body, "digest")?,
1806 }),
1807 "macos_spawn_inode" => {
1808 let device = ordered_field(&body, "device")
1809 .and_then(|value| match value {
1810 OrderedJsonValue::Number(number) => number.as_u64(),
1811 _ => None,
1812 })
1813 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1814 let inode = ordered_field(&body, "inode")
1815 .and_then(|value| match value {
1816 OrderedJsonValue::Number(number) => number.as_u64(),
1817 _ => None,
1818 })
1819 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1820 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1821 }
1822 "windows_spawn_file_id" => {
1823 let wire: RunningImageEvidenceWire = serde_json::from_value(
1824 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1825 )
1826 .map_err(|error| error.to_string())?;
1827 match wire {
1828 RunningImageEvidenceWire::WindowsSpawnFileId {
1829 volume_serial_number,
1830 file_id,
1831 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1832 volume_serial_number,
1833 file_id,
1834 }),
1835 _ => unreachable!(),
1836 }
1837 }
1838 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1839 }
1840}
1841
1842impl Serialize for ModuleDeclaredProvenance {
1843 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1844 where
1845 S: Serializer,
1846 {
1847 match self {
1848 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1849 build: build.clone(),
1850 }
1851 .serialize(serializer),
1852 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1853 Self::Unknown { body, .. } => body.serialize(serializer),
1854 }
1855 }
1856}
1857
1858impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1859 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1860 where
1861 D: serde::Deserializer<'de>,
1862 {
1863 let (tag, value) = read_tagged(deserializer, "status")?;
1864 match tag.as_str() {
1865 "reported" => match serde_json::from_value(value.into_value())
1866 .map_err(D::Error::custom)?
1867 {
1868 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1869 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1870 },
1871 "unverifiable" => {
1872 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1873 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1874 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1875 }
1876 }
1877 _ => Ok(Self::Unknown { tag, body: value }),
1878 }
1879 }
1880}
1881
1882impl Serialize for RunningImageAgreement {
1883 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1884 where
1885 S: Serializer,
1886 {
1887 match self {
1888 Self::Match { evidence } => RunningImageAgreementWire::Match {
1889 evidence: evidence.clone(),
1890 }
1891 .serialize(serializer),
1892 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1893 running: running.clone(),
1894 disk: disk.clone(),
1895 }
1896 .serialize(serializer),
1897 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1898 reason: reason.clone(),
1899 }
1900 .serialize(serializer),
1901 Self::Unknown { body, .. } => body.serialize(serializer),
1902 }
1903 }
1904}
1905
1906impl Serialize for ReloadPathAgreement {
1907 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1908 where
1909 S: Serializer,
1910 {
1911 match self {
1912 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1913 Self::Mismatch {
1914 configured,
1915 spawned_from,
1916 } => ReloadPathAgreementWire::Mismatch {
1917 configured: configured.clone(),
1918 spawned_from: spawned_from.clone(),
1919 }
1920 .serialize(serializer),
1921 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1922 reason: reason.clone(),
1923 }
1924 .serialize(serializer),
1925 Self::Unknown { body, .. } => body.serialize(serializer),
1926 }
1927 }
1928}
1929
1930impl Serialize for LaunchSpecAgreement {
1931 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1932 where
1933 S: Serializer,
1934 {
1935 match self {
1936 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1937 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1938 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1939 reason: reason.clone(),
1940 }
1941 .serialize(serializer),
1942 Self::Unknown { body, .. } => body.serialize(serializer),
1943 }
1944 }
1945}
1946
1947impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1948 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1949 where
1950 D: Deserializer<'de>,
1951 {
1952 let (tag, body) = read_tagged(deserializer, "status")?;
1953 match tag.as_str() {
1954 "match" => Ok(Self::Match),
1955 "mismatch" => Ok(Self::Mismatch),
1956 "unavailable" => match serde_json::from_value(body.into_value())
1957 .map_err(D::Error::custom)?
1958 {
1959 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1960 _ => unreachable!(),
1961 },
1962 _ => Ok(Self::Unknown { tag, body }),
1963 }
1964 }
1965}
1966
1967impl<'de> Deserialize<'de> for ReloadPathAgreement {
1968 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1969 where
1970 D: Deserializer<'de>,
1971 {
1972 let (tag, body) = read_tagged(deserializer, "status")?;
1973 match tag.as_str() {
1974 "match" => Ok(Self::Match),
1975 "mismatch" => {
1976 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1977 ReloadPathAgreementWire::Mismatch {
1978 configured,
1979 spawned_from,
1980 } => Ok(Self::Mismatch {
1981 configured,
1982 spawned_from,
1983 }),
1984 _ => unreachable!(),
1985 }
1986 }
1987 "unavailable" => match serde_json::from_value(body.into_value())
1988 .map_err(D::Error::custom)?
1989 {
1990 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1991 _ => unreachable!(),
1992 },
1993 _ => Ok(Self::Unknown { tag, body }),
1994 }
1995 }
1996}
1997
1998impl<'de> Deserialize<'de> for RunningImageAgreement {
1999 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2000 where
2001 D: serde::Deserializer<'de>,
2002 {
2003 let (tag, value) = read_tagged(deserializer, "status")?;
2004 match tag.as_str() {
2005 "match" => Ok(Self::Match {
2006 evidence: decode_running_image_evidence(
2007 ordered_field(&value, "evidence")
2008 .cloned()
2009 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
2010 )
2011 .map_err(D::Error::custom)?,
2012 }),
2013 "mismatch" => Ok(Self::Mismatch {
2014 running: decode_running_image_evidence(
2015 ordered_field(&value, "running")
2016 .cloned()
2017 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
2018 )
2019 .map_err(D::Error::custom)?,
2020 disk: decode_running_image_evidence(
2021 ordered_field(&value, "disk")
2022 .cloned()
2023 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
2024 )
2025 .map_err(D::Error::custom)?,
2026 }),
2027 "unavailable" => Ok(Self::Unavailable {
2028 reason: serde_json::from_value(
2029 ordered_field(&value, "reason")
2030 .cloned()
2031 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
2032 .into_value(),
2033 )
2034 .map_err(D::Error::custom)?,
2035 }),
2036 _ => Ok(Self::Unknown { tag, body: value }),
2037 }
2038 }
2039}
2040
2041impl Serialize for ChildResourceUsage {
2042 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2043 where
2044 S: Serializer,
2045 {
2046 match self {
2047 Self::Measured(reading) => {
2048 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
2049 }
2050 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
2051 reason: reason.clone(),
2052 }
2053 .serialize(serializer),
2054 Self::Unknown { body, .. } => body.serialize(serializer),
2055 }
2056 }
2057}
2058
2059impl<'de> Deserialize<'de> for ChildResourceUsage {
2060 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2061 where
2062 D: Deserializer<'de>,
2063 {
2064 let (tag, body) = read_tagged(deserializer, "status")?;
2065 match tag.as_str() {
2066 "measured" | "unavailable" => {
2067 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2068 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
2069 ChildResourceUsageWire::Unavailable { reason } => {
2070 Ok(Self::Unavailable { reason })
2071 }
2072 }
2073 }
2074 _ => Ok(Self::Unknown { tag, body }),
2075 }
2076 }
2077}
2078
2079impl Serialize for RunningImageEvidence {
2080 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2081 where
2082 S: Serializer,
2083 {
2084 match self {
2085 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
2086 digest: digest.clone(),
2087 }
2088 .serialize(serializer),
2089 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
2090 device: *device,
2091 inode: *inode,
2092 }
2093 .serialize(serializer),
2094 Self::WindowsSpawnFileId {
2095 volume_serial_number,
2096 file_id,
2097 } => RunningImageEvidenceWire::WindowsSpawnFileId {
2098 volume_serial_number: *volume_serial_number,
2099 file_id: *file_id,
2100 }
2101 .serialize(serializer),
2102 Self::Unknown { body, .. } => body.serialize(serializer),
2103 }
2104 }
2105}
2106
2107impl<'de> Deserialize<'de> for RunningImageEvidence {
2108 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2109 where
2110 D: serde::Deserializer<'de>,
2111 {
2112 let (tag, value) = read_tagged(deserializer, "method")?;
2113 match tag.as_str() {
2114 "linux_proc_sha256" => {
2115 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2116 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
2117 Ok(Self::LinuxProcSha256 { digest })
2118 }
2119 _ => unreachable!(),
2120 }
2121 }
2122 "macos_spawn_inode" => {
2123 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2124 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
2125 Ok(Self::MacosSpawnInode { device, inode })
2126 }
2127 _ => unreachable!(),
2128 }
2129 }
2130 "windows_spawn_file_id" => {
2131 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2132 RunningImageEvidenceWire::WindowsSpawnFileId {
2133 volume_serial_number,
2134 file_id,
2135 } => Ok(Self::WindowsSpawnFileId {
2136 volume_serial_number,
2137 file_id,
2138 }),
2139 _ => unreachable!(),
2140 }
2141 }
2142 _ => Ok(Self::Unknown { tag, body: value }),
2143 }
2144 }
2145}
2146
2147impl Serialize for SupervisorRouteConsumer {
2148 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2149 where
2150 S: Serializer,
2151 {
2152 match self {
2153 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
2154 module_id: module_id.clone(),
2155 }
2156 .serialize(serializer),
2157 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
2158 connection_id: *connection_id,
2159 }
2160 .serialize(serializer),
2161 Self::Unknown { body, .. } => body.serialize(serializer),
2162 }
2163 }
2164}
2165
2166impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
2167 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2168 where
2169 D: serde::Deserializer<'de>,
2170 {
2171 let (tag, value) = read_tagged(deserializer, "kind")?;
2172 match tag.as_str() {
2173 "reserved" => {
2174 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2175 SupervisorRouteConsumerWire::Reserved { module_id } => {
2176 Ok(Self::Reserved { module_id })
2177 }
2178 _ => unreachable!(),
2179 }
2180 }
2181 "direct" => {
2182 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2183 SupervisorRouteConsumerWire::Direct { connection_id } => {
2184 Ok(Self::Direct { connection_id })
2185 }
2186 _ => unreachable!(),
2187 }
2188 }
2189 _ => Ok(Self::Unknown { tag, body: value }),
2190 }
2191 }
2192}
2193
2194impl Serialize for StderrCaptureState {
2195 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2196 where
2197 S: Serializer,
2198 {
2199 match self {
2200 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
2201 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
2202 reason: reason.clone(),
2203 }
2204 .serialize(serializer),
2205 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
2206 reason: reason.clone(),
2207 }
2208 .serialize(serializer),
2209 Self::Unknown { body, .. } => body.serialize(serializer),
2210 }
2211 }
2212}
2213
2214impl<'de> Deserialize<'de> for StderrCaptureState {
2215 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2216 where
2217 D: serde::Deserializer<'de>,
2218 {
2219 let (tag, value) = read_tagged(deserializer, "state")?;
2220 match tag.as_str() {
2221 "captured" => {
2222 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2223 StderrCaptureStateWire::Captured => Ok(Self::Captured),
2224 _ => unreachable!(),
2225 }
2226 }
2227 "incomplete" => match serde_json::from_value(value.into_value())
2228 .map_err(D::Error::custom)?
2229 {
2230 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
2231 _ => unreachable!(),
2232 },
2233 "not_captured" => match serde_json::from_value(value.into_value())
2234 .map_err(D::Error::custom)?
2235 {
2236 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
2237 _ => unreachable!(),
2238 },
2239 _ => Ok(Self::Unknown { tag, body: value }),
2240 }
2241 }
2242}
2243
2244impl Serialize for StderrTailEntry {
2245 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2246 where
2247 S: Serializer,
2248 {
2249 match self {
2250 Self::Line {
2251 text,
2252 truncated,
2253 at_ms,
2254 } => StderrTailEntryWire::Line {
2255 text: text.clone(),
2256 truncated: *truncated,
2257 at_ms: *at_ms,
2258 }
2259 .serialize(serializer),
2260 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
2261 Self::Unknown { body, .. } => body.serialize(serializer),
2262 }
2263 }
2264}
2265
2266impl<'de> Deserialize<'de> for StderrTailEntry {
2267 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2268 where
2269 D: serde::Deserializer<'de>,
2270 {
2271 let (tag, value) = read_tagged(deserializer, "kind")?;
2272 match tag.as_str() {
2273 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2274 StderrTailEntryWire::Line {
2275 text,
2276 truncated,
2277 at_ms,
2278 } => Ok(Self::Line {
2279 text,
2280 truncated,
2281 at_ms,
2282 }),
2283 _ => unreachable!(),
2284 },
2285 "process_start" => {
2286 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2287 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
2288 _ => unreachable!(),
2289 }
2290 }
2291 _ => Ok(Self::Unknown { tag, body: value }),
2292 }
2293 }
2294}
2295
2296fn is_zero_u64(value: &u64) -> bool {
2297 *value == 0
2298}
2299
2300fn default_true() -> bool {
2301 true
2302}
2303
2304#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2306pub struct TerminalHistory {
2307 pub daemon_started_at_ms: u64,
2309 pub entries: Vec<TerminalEntry>,
2310 #[serde(default, skip_serializing_if = "is_zero_u64")]
2313 pub dropped: u64,
2314 #[serde(default, skip_serializing_if = "is_zero_u64")]
2317 pub journal_skipped_lines: u64,
2318 #[serde(default, skip_serializing_if = "is_zero_u64")]
2320 pub journal_read_errors: u64,
2321 #[serde(default, skip_serializing_if = "is_zero_u64")]
2323 pub journal_write_failures: u64,
2324}
2325
2326#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2328pub struct TerminalEntry {
2329 #[serde(default, skip_serializing_if = "Option::is_none")]
2332 pub daemon_incarnation: Option<String>,
2333 #[serde(default, skip_serializing_if = "Option::is_none")]
2334 pub exit_code: Option<i32>,
2335 #[serde(default, skip_serializing_if = "Option::is_none")]
2336 pub exit_signal: Option<i32>,
2337 pub at_ms: u64,
2338 pub disposition: TerminalDisposition,
2339 #[serde(default, skip_serializing_if = "Option::is_none")]
2343 pub exit_kind: Option<TerminalExitKind>,
2344 #[serde(default, skip_serializing_if = "Option::is_none")]
2351 pub disposition_detail: Option<String>,
2352}
2353
2354#[derive(Debug, Clone, PartialEq, Eq)]
2359pub enum TerminalExitKind {
2360 Clean,
2361 Crash,
2362 DeliberateSeverance,
2363 Unknown(String),
2364}
2365
2366impl TerminalExitKind {
2367 fn wire_name(&self) -> &str {
2368 match self {
2369 Self::Clean => "clean",
2370 Self::Crash => "crash",
2371 Self::DeliberateSeverance => "deliberate_severance",
2372 Self::Unknown(value) => value,
2373 }
2374 }
2375}
2376
2377impl Serialize for TerminalExitKind {
2378 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2379 where
2380 S: serde::Serializer,
2381 {
2382 serializer.serialize_str(self.wire_name())
2383 }
2384}
2385
2386impl<'de> Deserialize<'de> for TerminalExitKind {
2387 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2388 where
2389 D: serde::Deserializer<'de>,
2390 {
2391 let value = String::deserialize(deserializer)?;
2392 Ok(match value.as_str() {
2393 "clean" => Self::Clean,
2394 "crash" => Self::Crash,
2395 "deliberate_severance" => Self::DeliberateSeverance,
2396 _ => Self::Unknown(value),
2397 })
2398 }
2399}
2400
2401open_string_enum! {
2402 TerminalDisposition {
2404 Stopped => "stopped",
2405 Disabled => "disabled",
2406 Failed => "failed",
2407 Restarting => "restarting",
2408 DaemonShutdown => "daemon_shutdown",
2413 }
2414}
2415
2416#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2417#[serde(rename_all = "snake_case")]
2418pub enum PollKind {
2419 Status,
2420 Liveness,
2421}
2422
2423#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2435#[non_exhaustive]
2436pub struct CatalogEntry {
2437 pub module_id: String,
2438 #[serde(default, skip_serializing_if = "Option::is_none")]
2440 pub display_name: Option<String>,
2441 #[serde(default = "default_true")]
2452 pub ready: bool,
2453 #[serde(default, skip_serializing_if = "Option::is_none")]
2457 pub not_ready: Option<NotReadyReason>,
2458 #[serde(default, skip_serializing_if = "Option::is_none")]
2479 pub module_version: Option<String>,
2480 #[serde(default, skip_serializing_if = "Option::is_none")]
2483 pub provenance: Option<ManifestProvenance>,
2484 pub roles: Vec<ProviderRole>,
2485 pub control_ops: Vec<String>,
2486 #[serde(default, skip_serializing_if = "Option::is_none")]
2491 pub capabilities: Option<CapabilityDeclarations>,
2492 #[serde(default, skip_serializing_if = "Option::is_none")]
2495 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2496 #[serde(default, skip_serializing_if = "Option::is_none")]
2500 pub events: Option<Vec<EventDeclaration>>,
2501 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2504 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2505 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2508 pub operation_payload: BTreeMap<String, OperationPayload>,
2509 #[serde(default, skip_serializing_if = "Option::is_none")]
2515 pub flow_operations: Option<Vec<String>>,
2516 #[serde(default, skip_serializing_if = "Option::is_none")]
2518 pub operation_deferral: Option<BTreeMap<String, bool>>,
2519 #[serde(default, skip_serializing_if = "Option::is_none")]
2525 pub confirm_operations: Option<Vec<String>>,
2526 #[serde(default, skip_serializing_if = "Option::is_none")]
2529 pub rich_ui: Option<RichUiDescriptor>,
2530 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2533 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2534 #[serde(default, skip_serializing_if = "is_false")]
2539 pub nonce_verified: bool,
2540 #[serde(default, skip_serializing_if = "Option::is_none")]
2543 pub incarnation: Option<String>,
2544 #[serde(
2545 default,
2546 skip_serializing_if = "Option::is_none",
2547 deserialize_with = "deserialize_optional_attestation_integer"
2548 )]
2549 pub spawn: Option<u64>,
2550 #[serde(default, skip_serializing_if = "Option::is_none")]
2551 pub first_party: Option<bool>,
2552 #[serde(default, skip_serializing_if = "Option::is_none")]
2553 pub origin: Option<CatalogOrigin>,
2554 #[serde(default, skip_serializing_if = "Option::is_none")]
2555 pub requested_declarations_digest: Option<String>,
2556 #[serde(default, skip_serializing_if = "Option::is_none")]
2557 pub approved_declarations_digest: Option<String>,
2558 #[serde(default, skip_serializing_if = "Option::is_none")]
2561 pub approved_declarations: Option<ProviderDeclarations>,
2562 #[serde(default, skip_serializing_if = "Option::is_none")]
2563 pub requested_declarations: Option<ProviderDeclarations>,
2564}
2565
2566impl CatalogEntry {
2567 #[must_use]
2569 pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2570 self.display_name = display_name;
2571 self
2572 }
2573
2574 #[must_use]
2576 pub fn new(
2577 module_id: impl Into<String>,
2578 roles: Vec<ProviderRole>,
2579 control_ops: Vec<String>,
2580 ) -> Self {
2581 Self {
2582 module_id: module_id.into(),
2583 ready: default_true(),
2584 display_name: None,
2585 not_ready: None,
2586 module_version: None,
2587 provenance: None,
2588 roles,
2589 control_ops,
2590 capabilities: None,
2591 self_signals: None,
2592 events: None,
2593 operation_delivery: BTreeMap::new(),
2594 operation_payload: BTreeMap::new(),
2595 flow_operations: None,
2596 operation_deferral: None,
2597 confirm_operations: None,
2598 rich_ui: None,
2599 role_declarations: BTreeMap::new(),
2600 nonce_verified: false,
2601 incarnation: None,
2602 spawn: None,
2603 first_party: None,
2604 origin: None,
2605 requested_declarations_digest: None,
2606 approved_declarations_digest: None,
2607 approved_declarations: None,
2608 requested_declarations: None,
2609 }
2610 }
2611
2612 #[must_use]
2614 pub fn with_operation_payload(
2615 mut self,
2616 operation_payload: BTreeMap<String, OperationPayload>,
2617 ) -> Self {
2618 self.operation_payload = operation_payload;
2619 self
2620 }
2621
2622 #[must_use]
2625 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2626 self.flow_operations = flow_operations;
2627 self
2628 }
2629
2630 #[must_use]
2632 pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
2633 self.operation_deferral = operations;
2634 self
2635 }
2636
2637 #[must_use]
2640 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2641 self.confirm_operations = confirm_operations;
2642 self
2643 }
2644
2645 #[must_use]
2647 pub fn with_ready(mut self, ready: bool) -> Self {
2648 self.ready = ready;
2649 self
2650 }
2651
2652 #[must_use]
2654 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2655 self.not_ready = not_ready;
2656 self
2657 }
2658
2659 #[must_use]
2661 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2662 self.module_version = module_version;
2663 self
2664 }
2665
2666 #[must_use]
2668 pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2669 self.provenance = provenance;
2670 self
2671 }
2672
2673 #[must_use]
2675 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2676 self.capabilities = capabilities;
2677 self
2678 }
2679
2680 #[must_use]
2682 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2683 self.self_signals = self_signals;
2684 self
2685 }
2686
2687 #[must_use]
2689 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2690 self.events = events;
2691 self
2692 }
2693
2694 #[must_use]
2697 pub fn with_operation_delivery(
2698 mut self,
2699 operation_delivery: BTreeMap<String, OperationDelivery>,
2700 ) -> Self {
2701 self.operation_delivery = operation_delivery;
2702 self
2703 }
2704
2705 #[must_use]
2707 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2708 self.rich_ui = rich_ui;
2709 self
2710 }
2711
2712 #[must_use]
2714 pub fn with_role_declarations(
2715 mut self,
2716 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2717 ) -> Self {
2718 self.role_declarations = role_declarations;
2719 self
2720 }
2721
2722 #[must_use]
2724 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2725 self.nonce_verified = nonce_verified;
2726 self
2727 }
2728}
2729
2730fn is_false(value: &bool) -> bool {
2731 !value
2732}
2733
2734#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2736pub struct NotReadyReason {
2737 pub reason: String,
2742 #[serde(default, skip_serializing_if = "Option::is_none")]
2745 pub capability: Option<String>,
2746}
2747
2748impl NotReadyReason {
2749 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2750 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2751}
2752
2753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2754pub struct CapabilityRequirementStatus {
2755 pub consumer: String,
2756 pub capability: String,
2757 pub need: String,
2758 pub verdict: String,
2759 pub episode_seq: u64,
2760 pub config_satisfiable: bool,
2761 pub runtime_available: bool,
2762 pub detail: String,
2763}
2764
2765#[non_exhaustive]
2770#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2771#[serde(rename_all = "snake_case")]
2772pub enum PendingModuleApply {
2773 NextSupervision,
2774 WithNextLaunchOrHealthChange,
2775 DaemonRestart,
2776 ConfigGate,
2777 #[serde(other)]
2778 Other,
2779}
2780
2781#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2783pub struct SupervisorPendingField {
2784 pub field: String,
2785 pub applies: PendingModuleApply,
2786 #[serde(default, skip_serializing_if = "Option::is_none")]
2787 pub value: Option<serde_json::Value>,
2788}
2789
2790#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2791pub struct SupervisorPendingModule {
2792 pub module_id: String,
2793 pub fields: Vec<SupervisorPendingField>,
2794}
2795
2796#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2797pub struct SupervisorRescanResult {
2798 pub added: Vec<String>,
2799 pub removed: Vec<String>,
2800 pub changed_pending_reload: Vec<String>,
2801 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2803 pub changed_pending: Vec<SupervisorPendingModule>,
2804 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2817 pub enabled_changes: Vec<String>,
2818 pub unchanged: u32,
2819 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2827 pub preview: bool,
2828 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2846 pub restart_required: Vec<String>,
2847 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2851 pub capability_warnings: Vec<String>,
2852 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2859 pub module_actions: Vec<RescanModuleAction>,
2860 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2864 pub earlier_pending: Vec<String>,
2865 #[serde(default, skip_serializing_if = "Option::is_none")]
2868 pub expect: Option<RescanExpect>,
2869}
2870
2871#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2887#[serde(rename_all = "snake_case")]
2888pub enum ModuleProtocol {
2889 #[default]
2893 Subc,
2894 None,
2903}
2904
2905#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2917#[non_exhaustive]
2918pub struct SupervisorEntry {
2919 #[serde(default, skip_serializing_if = "Option::is_none")]
2921 pub script: Option<ScriptModuleStatus>,
2922 #[serde(default, skip_serializing_if = "Option::is_none")]
2925 pub waiting_for_previous_pid: Option<u32>,
2926 pub module_id: String,
2927 pub state: String,
2928 #[serde(default, skip_serializing_if = "Option::is_none")]
2932 pub admission_refused: Option<String>,
2933 #[serde(default, skip_serializing_if = "Option::is_none")]
2937 pub next_retry_at_ms: Option<u64>,
2938 pub enabled: bool,
2939 #[serde(default, skip_serializing_if = "Option::is_none")]
2942 pub configured_enabled: Option<bool>,
2943 pub live: bool,
2953 #[serde(default)]
2957 pub protocol: ModuleProtocol,
2958 #[serde(default, skip_serializing_if = "Option::is_none")]
2961 pub launch_nonce_env: Option<bool>,
2962 #[serde(default, skip_serializing_if = "Option::is_none")]
2968 pub launch_nonce_source: Option<String>,
2969 pub health: SupervisorHealthStatus,
2970 #[serde(default, skip_serializing_if = "Option::is_none")]
2973 pub pending_reload: Option<PendingReloadVerdict>,
2974 #[serde(default)]
2980 pub last_probe_ms: Option<u64>,
2981 #[serde(default, skip_serializing_if = "Option::is_none")]
2985 pub last_exit_code: Option<i32>,
2986 #[serde(default, skip_serializing_if = "Option::is_none")]
2990 pub last_exit_signal: Option<i32>,
2991 #[serde(default, skip_serializing_if = "Option::is_none")]
2995 pub last_exit_ms: Option<u64>,
2996 #[serde(default, skip_serializing_if = "Option::is_none")]
2999 pub last_exit_kind: Option<TerminalExitKind>,
3000 #[serde(default, skip_serializing_if = "Option::is_none")]
3017 pub restart_count: Option<u32>,
3018 #[serde(default, skip_serializing_if = "Option::is_none")]
3021 pub max_restarts: Option<u32>,
3022 #[serde(default, skip_serializing_if = "Option::is_none")]
3025 pub lifetime_restarts: Option<u32>,
3026 #[serde(default, skip_serializing_if = "Option::is_none")]
3030 pub spawn_generation: Option<u64>,
3031 #[serde(default, skip_serializing_if = "Option::is_none")]
3041 pub restart_window_secs: Option<u64>,
3042 #[serde(default, skip_serializing_if = "Option::is_none")]
3046 pub drain_timeout_ms: Option<u64>,
3047 #[serde(default, skip_serializing_if = "Option::is_none")]
3050 pub restart_backoff_ms: Option<u64>,
3051 #[serde(default, skip_serializing_if = "Option::is_none")]
3054 pub restart_max_backoff_ms: Option<u64>,
3055 #[serde(default, skip_serializing_if = "Option::is_none")]
3068 pub resources: Option<ChildResourceUsage>,
3069 #[serde(default, skip_serializing_if = "Option::is_none")]
3071 pub tree: Option<TreeReading>,
3072 #[serde(default, skip_serializing_if = "Option::is_none")]
3078 pub tree_unavailable: Option<String>,
3079 #[serde(default, skip_serializing_if = "Option::is_none")]
3081 pub cpu_last_hour: Option<CpuLastHour>,
3082 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3084 pub pending: Vec<SupervisorPendingField>,
3085}
3086
3087impl SupervisorEntry {
3088 #[must_use]
3089 pub fn with_script(mut self, script: Option<ScriptModuleStatus>) -> Self {
3090 self.script = script;
3091 self
3092 }
3093 #[must_use]
3095 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3096 self.next_retry_at_ms = next_retry_at_ms;
3097 self
3098 }
3099
3100 #[must_use]
3102 pub fn new(
3103 module_id: impl Into<String>,
3104 state: impl Into<String>,
3105 enabled: bool,
3106 live: bool,
3107 health: SupervisorHealthStatus,
3108 ) -> Self {
3109 Self {
3110 module_id: module_id.into(),
3111 script: None,
3112 state: state.into(),
3113 admission_refused: None,
3114 next_retry_at_ms: None,
3115 waiting_for_previous_pid: None,
3116 enabled,
3117 configured_enabled: None,
3118 live,
3119 protocol: ModuleProtocol::default(),
3120 launch_nonce_env: None,
3121 launch_nonce_source: None,
3122 health,
3123 pending_reload: None,
3124 last_probe_ms: None,
3125 last_exit_code: None,
3126 last_exit_signal: None,
3127 last_exit_ms: None,
3128 last_exit_kind: None,
3129 restart_count: None,
3130 max_restarts: None,
3131 lifetime_restarts: None,
3132 spawn_generation: None,
3133 restart_window_secs: None,
3134 drain_timeout_ms: None,
3135 restart_backoff_ms: None,
3136 restart_max_backoff_ms: None,
3137 resources: None,
3138 tree: None,
3139 tree_unavailable: None,
3140 cpu_last_hour: None,
3141 pending: Vec::new(),
3142 }
3143 }
3144
3145 #[must_use]
3147 pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3148 self.admission_refused = reason;
3149 self
3150 }
3151
3152 #[must_use]
3154 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3155 self.protocol = protocol;
3156 self
3157 }
3158
3159 #[must_use]
3161 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3162 self.configured_enabled = configured_enabled;
3163 self
3164 }
3165
3166 #[must_use]
3168 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3169 self.launch_nonce_env = launch_nonce_env;
3170 self
3171 }
3172
3173 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3174 self.launch_nonce_source = source;
3175 self
3176 }
3177
3178 #[must_use]
3179 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3180 self.waiting_for_previous_pid = pid;
3181 self
3182 }
3183
3184 #[must_use]
3186 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3187 self.pending_reload = pending_reload;
3188 self
3189 }
3190
3191 #[must_use]
3193 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3194 self.last_probe_ms = last_probe_ms;
3195 self
3196 }
3197
3198 #[must_use]
3200 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3201 self.last_exit_code = last_exit_code;
3202 self
3203 }
3204
3205 #[must_use]
3207 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3208 self.last_exit_signal = last_exit_signal;
3209 self
3210 }
3211
3212 #[must_use]
3214 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3215 self.last_exit_ms = last_exit_ms;
3216 self
3217 }
3218
3219 #[must_use]
3221 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3222 self.last_exit_kind = last_exit_kind;
3223 self
3224 }
3225
3226 #[must_use]
3228 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3229 self.restart_count = restart_count;
3230 self
3231 }
3232
3233 #[must_use]
3235 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3236 self.max_restarts = max_restarts;
3237 self
3238 }
3239
3240 #[must_use]
3242 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3243 self.lifetime_restarts = lifetime_restarts;
3244 self
3245 }
3246
3247 #[must_use]
3249 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3250 self.spawn_generation = spawn_generation;
3251 self
3252 }
3253
3254 #[must_use]
3256 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3257 self.restart_window_secs = restart_window_secs;
3258 self
3259 }
3260
3261 #[must_use]
3263 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3264 self.drain_timeout_ms = drain_timeout_ms;
3265 self
3266 }
3267
3268 #[must_use]
3270 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3271 self.restart_backoff_ms = restart_backoff_ms;
3272 self
3273 }
3274
3275 #[must_use]
3277 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3278 self.restart_max_backoff_ms = restart_max_backoff_ms;
3279 self
3280 }
3281
3282 #[must_use]
3284 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3285 self.resources = resources;
3286 self
3287 }
3288
3289 #[must_use]
3291 pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3292 self.tree = tree;
3293 self
3294 }
3295
3296 #[must_use]
3298 pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3299 self.tree_unavailable = reason;
3300 self
3301 }
3302}
3303
3304#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3306pub struct ScriptModuleStatus {
3307 pub runtime: String,
3308 pub bun_version: Option<String>,
3309 pub path: PathBuf,
3310 pub sha256: Option<String>,
3311 pub size: Option<u64>,
3312 pub needs_review: bool,
3313}
3314
3315#[cfg(test)]
3316mod script_status_tests {
3317 use super::*;
3318
3319 #[test]
3320 fn script_status_roundtrips_and_old_supervisor_entries_remain_readable() {
3321 let old = SupervisorEntry::new(
3322 "example",
3323 "running",
3324 true,
3325 true,
3326 SupervisorHealthStatus::Unknown,
3327 );
3328 let value = serde_json::to_value(&old).unwrap();
3329 assert!(value.get("script").is_none());
3330 assert!(serde_json::from_value::<SupervisorEntry>(value)
3331 .unwrap()
3332 .script
3333 .is_none());
3334 let current = old.with_script(Some(ScriptModuleStatus {
3335 runtime: "bun".into(),
3336 bun_version: None,
3337 path: "bundle.js".into(),
3338 sha256: Some("ab".repeat(32)),
3339 size: Some(3),
3340 needs_review: true,
3341 }));
3342 let decoded: SupervisorEntry =
3343 serde_json::from_slice(&serde_json::to_vec(¤t).unwrap()).unwrap();
3344 assert_eq!(decoded, current);
3345 }
3346}
3347
3348#[derive(Debug, Clone, PartialEq)]
3351pub enum ChildResourceUsage {
3352 Measured(ChildResourceReading),
3353 Unavailable {
3354 reason: ChildResourceUnavailableReason,
3355 },
3356 Unknown {
3359 tag: String,
3360 body: OrderedJsonObject,
3361 },
3362}
3363
3364#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3367#[non_exhaustive]
3368pub struct ChildResourceReading {
3369 pub memory_bytes: u64,
3372 pub memory_kind: ChildMemoryKind,
3373 #[serde(default, skip_serializing_if = "Option::is_none")]
3376 pub swap_bytes: Option<u64>,
3377 pub cpu_user_ms: u64,
3381 pub cpu_system_ms: u64,
3384}
3385
3386impl ChildResourceReading {
3387 #[must_use]
3389 pub fn new(
3390 memory_bytes: u64,
3391 memory_kind: ChildMemoryKind,
3392 cpu_user_ms: u64,
3393 cpu_system_ms: u64,
3394 ) -> Self {
3395 Self {
3396 memory_bytes,
3397 memory_kind,
3398 cpu_user_ms,
3399 cpu_system_ms,
3400 swap_bytes: None,
3401 }
3402 }
3403
3404 #[must_use]
3406 pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3407 self.swap_bytes = swap_bytes;
3408 self
3409 }
3410}
3411
3412open_string_enum! {
3413 ChildMemoryKind {
3415 PhysFootprint => "phys_footprint",
3419 ResidentSet => "resident_set",
3422 WindowsWorkingSet => "windows_working_set",
3425 }
3426}
3427
3428open_string_enum! {
3429 ChildResourceUnavailableReason {
3431 NotRunning => "not_running",
3433 UnsupportedPlatform => "unsupported_platform",
3435 Unreadable => "unreadable",
3438 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3441 }
3442}
3443
3444#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3445#[serde(rename_all = "snake_case")]
3446pub enum SupervisorHealthStatus {
3447 Ok,
3448 Degraded,
3449 Failing,
3450 Unresponsive,
3451 Unknown,
3452}
3453
3454#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3455pub struct SupervisorHealthEntry {
3456 pub module_id: String,
3457 pub status: SupervisorHealthStatus,
3458 #[serde(default, skip_serializing_if = "Option::is_none")]
3464 pub detail: Option<String>,
3465 #[serde(default, skip_serializing_if = "Option::is_none")]
3470 pub metrics: Option<serde_json::Value>,
3471 pub consecutive_failures: u32,
3472 #[serde(default)]
3475 pub late_answer_count: u64,
3476 #[serde(default, skip_serializing_if = "Option::is_none")]
3478 pub last_late_answer_latency_ms: Option<u64>,
3479 #[serde(default)]
3484 pub last_action: Option<String>,
3485 #[serde(default)]
3488 pub last_action_ms: Option<u64>,
3489 #[serde(default, skip_serializing_if = "Option::is_none")]
3502 pub last_probe_ms: Option<u64>,
3503}
3504
3505#[cfg(test)]
3506mod tests {
3507 #[test]
3508 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3509 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3510 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3511 assert_eq!(decoded.configured_enabled, None);
3512 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3513 }
3514
3515 #[test]
3516 fn configured_enabled_values_round_trip_in_list() {
3517 for enabled in [false, true] {
3518 let entry = SupervisorEntry::new(
3519 "provider",
3520 "running",
3521 true,
3522 true,
3523 SupervisorHealthStatus::Unknown,
3524 )
3525 .with_configured_enabled(Some(enabled));
3526 let entry_json = serde_json::to_value(&entry).unwrap();
3527 assert_eq!(entry_json["configured_enabled"], enabled);
3528 assert_eq!(
3529 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3530 entry
3531 );
3532 }
3533 }
3534
3535 #[test]
3536 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3537 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3538 volume_serial_number: u64::MAX,
3539 file_id: [
3540 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3541 ],
3542 };
3543 let agreement = super::RunningImageAgreement::Match { evidence };
3544 let encoded = serde_json::to_string(&agreement).unwrap();
3545 assert!(encoded.contains("windows_spawn_file_id"));
3546 assert_eq!(
3547 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3548 agreement
3549 );
3550 }
3551
3552 #[test]
3553 fn unix_running_image_evidence_keeps_original_wire_bytes() {
3554 assert_eq!(
3555 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3556 device: 7,
3557 inode: 11
3558 })
3559 .unwrap(),
3560 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3561 );
3562 assert_eq!(
3563 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3564 digest: "abc".to_owned()
3565 })
3566 .unwrap(),
3567 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3568 );
3569 }
3570 use super::*;
3571 use subc_protocol::{BindIdentity, RouteTarget};
3572
3573 #[test]
3574 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3575 let entry = TerminalEntry {
3576 daemon_incarnation: Some("daemon-before-restart".into()),
3577 exit_code: Some(1),
3578 exit_signal: None,
3579 at_ms: 1_700_000_000_123,
3580 disposition: TerminalDisposition::Restarting,
3581 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3582 disposition_detail: None,
3583 };
3584 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3585 assert_eq!(
3586 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3587 ["exit_kind"],
3588 "deliberate_severance"
3589 );
3590
3591 #[derive(serde::Deserialize)]
3592 struct LegacyTerminalEntry {
3593 exit_code: Option<i32>,
3594 exit_signal: Option<i32>,
3595 at_ms: u64,
3596 disposition: TerminalDisposition,
3597 }
3598
3599 let decoded: LegacyTerminalEntry =
3600 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3601 assert_eq!(decoded.exit_code, Some(1));
3602 assert_eq!(decoded.exit_signal, None);
3603 assert_eq!(decoded.at_ms, 1_700_000_000_123);
3604 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3605
3606 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3607 let future: TerminalEntry =
3608 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3609 assert_eq!(
3610 future.exit_kind,
3611 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3612 );
3613 }
3614
3615 #[test]
3616 fn terminal_incarnation_is_optional_for_older_daemons() {
3617 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3618 "at_ms": 123,
3619 "disposition": "stopped"
3620 }))
3621 .unwrap();
3622 let encoded = serde_json::to_value(&entry).unwrap();
3623 assert_eq!(
3624 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3625 (None, None)
3626 );
3627 }
3628
3629 #[test]
3630 fn route_poll_uses_kind_field() {
3631 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3632 route_channel: 7,
3633 route_epoch: 11,
3634 kind: PollKind::Status,
3635 })
3636 .unwrap();
3637
3638 assert_eq!(body["op"], "route.poll");
3639 assert_eq!(body["route_epoch"], 11);
3640 assert_eq!(body["kind"], "status");
3641 assert!(body.get("op").is_some());
3642 }
3643
3644 #[test]
3645 fn route_open_is_internally_tagged() {
3646 let request = ClientControlRequest::RouteOpen {
3647 busy_refusals: None,
3648 target: RouteTarget::ToolProvider {
3649 module_id: "aft".to_string(),
3650 },
3651 identity: BindIdentity::new("opencode", "session-1"),
3652 consumer_identity: None,
3653 consumer_capabilities: None,
3654 role_versions: None,
3655 admission_facts: None,
3656 scope: None,
3657 };
3658
3659 let body = serde_json::to_value(request).unwrap();
3660 assert_eq!(body["op"], "route.open");
3661 assert_eq!(body["target"]["kind"], "tool_provider");
3662 assert!(body.get("consumer_identity").is_none());
3663 assert!(body.get("consumer_capabilities").is_none());
3664 assert!(body.get("role_versions").is_none());
3665 }
3666
3667 #[test]
3668 fn route_open_without_optional_fields_still_decodes() {
3669 let body = serde_json::json!({
3670 "op": "route.open",
3671 "target": { "kind": "tool_provider", "module_id": "aft" },
3672 "identity": {
3673 "project_root": "/tmp/project",
3674 "harness": "opencode",
3675 "session": "session-1"
3676 }
3677 });
3678
3679 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3680 let ClientControlRequest::RouteOpen {
3681 consumer_identity,
3682 consumer_capabilities,
3683 role_versions,
3684 admission_facts,
3685 ..
3686 } = decoded
3687 else {
3688 panic!("decoded wrong request variant");
3689 };
3690 assert_eq!(consumer_identity, None);
3691 assert_eq!(consumer_capabilities, None);
3692 assert_eq!(role_versions, None);
3693 assert_eq!(admission_facts, None);
3694 }
3695
3696 #[test]
3697 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3698 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3699 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3700 match decoded {
3701 ClientControlPush::RouteClosed {
3702 excluded_subscriptions,
3703 terminal,
3704 ..
3705 } => {
3706 assert_eq!(excluded_subscriptions, 0);
3707 assert_eq!(terminal, None);
3708 }
3709 other => panic!("unexpected push: {other:?}"),
3710 }
3711 assert!(!serde_json::to_string(&decoded)
3712 .unwrap()
3713 .contains("terminal"));
3714 }
3715
3716 #[test]
3717 fn old_route_closed_decoder_ignores_new_terminal_field() {
3718 #[derive(serde::Deserialize)]
3719 #[serde(tag = "op")]
3720 enum LegacyClientControlPush {
3721 #[serde(rename = "route.closed")]
3722 RouteClosed {
3723 module_id: String,
3724 reason: RouteCloseReason,
3725 drained: bool,
3726 abandoned: u32,
3727 },
3728 }
3729
3730 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3731 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3732 match decoded {
3733 LegacyClientControlPush::RouteClosed {
3734 module_id,
3735 reason,
3736 drained,
3737 abandoned,
3738 } => {
3739 assert_eq!(module_id, "aft-tools");
3740 assert_eq!(reason, RouteCloseReason::Crash);
3741 assert!(!drained);
3742 assert_eq!(abandoned, 0);
3743 }
3744 }
3745 }
3746
3747 #[test]
3748 fn supervisor_routes_is_a_control_plane_request() {
3749 let body = serde_json::json!({
3750 "op": "supervisor.routes",
3751 "module_id": "aft"
3752 });
3753
3754 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3755 assert_eq!(serde_json::to_value(request).unwrap(), body);
3756 }
3757
3758 #[test]
3759 fn diagnostic_string_enums_retain_unknown_wire_values() {
3760 let reason: RunningImageUnavailableReason =
3761 serde_json::from_str("\"future_reason\"").unwrap();
3762 let disposition: TerminalDisposition =
3763 serde_json::from_str("\"future_disposition\"").unwrap();
3764
3765 assert_eq!(
3766 reason,
3767 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3768 );
3769 assert_eq!(
3770 disposition,
3771 TerminalDisposition::Unknown("future_disposition".to_string())
3772 );
3773 }
3774
3775 #[test]
3776 fn diagnostic_string_enums_preserve_existing_wire_names() {
3777 let names = [
3778 (RunningImageUnavailableReason::NotRunning, "not_running"),
3779 (
3780 RunningImageUnavailableReason::UnsupportedPlatform,
3781 "unsupported_platform",
3782 ),
3783 (
3784 RunningImageUnavailableReason::RunningExecutableUnreadable,
3785 "running_executable_unreadable",
3786 ),
3787 (
3788 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3789 "running_executable_permission_denied",
3790 ),
3791 (
3792 RunningImageUnavailableReason::ProcessHidden,
3793 "process_hidden",
3794 ),
3795 (
3796 RunningImageUnavailableReason::SpawnedPathUnreadable,
3797 "spawned_path_unreadable",
3798 ),
3799 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3800 (
3801 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3802 "process_identity_unconfirmed",
3803 ),
3804 ];
3805 for (value, expected) in names {
3806 let wire = serde_json::to_string(&value).unwrap();
3807 assert_eq!(wire, format!("\"{expected}\""));
3808 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3809 assert_eq!(decoded, value);
3810 }
3811
3812 for (value, expected) in [
3813 (TerminalDisposition::Stopped, "stopped"),
3814 (TerminalDisposition::Disabled, "disabled"),
3815 (TerminalDisposition::Failed, "failed"),
3816 (TerminalDisposition::Restarting, "restarting"),
3817 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3818 ] {
3819 let wire = serde_json::to_string(&value).unwrap();
3820 assert_eq!(wire, format!("\"{expected}\""));
3821 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3822 assert_eq!(decoded, value);
3823 }
3824 }
3825
3826 #[test]
3827 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3828 let entry = SupervisorEntry::new(
3829 "waiting-module",
3830 "starting",
3831 true,
3832 false,
3833 SupervisorHealthStatus::Unknown,
3834 );
3835 let old_wire = serde_json::to_value(&entry).unwrap();
3836 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3837 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3838 assert_eq!(decoded.waiting_for_previous_pid, None);
3839 let entry = entry.with_waiting_for_previous_pid(Some(42));
3840 let wire = serde_json::to_value(&entry).unwrap();
3841 assert_eq!(wire["waiting_for_previous_pid"], 42);
3842 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3843 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3844 }
3845
3846 #[test]
3847 fn diagnostic_string_enums_reject_non_string_bodies() {
3848 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3849 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3850 }
3851
3852 #[test]
3853 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3854 let body = serde_json::json!({
3855 "op": "supervisor.provenance",
3856 "daemon": {
3857 "daemon_build": {},
3858 "daemon_observed": {
3859 "running_image": {
3860 "status": "unavailable",
3861 "reason": "not_running"
3862 }
3863 }
3864 },
3865 "modules": [
3866 {
3867 "module_id": "future",
3868 "module_declared": { "status": "unverifiable" },
3869 "daemon_observed": {
3870 "running_image": {
3871 "status": "unavailable",
3872 "reason": "future_reason"
3873 }
3874 }
3875 },
3876 {
3877 "module_id": "healthy-a",
3878 "module_declared": { "status": "unverifiable" },
3879 "daemon_observed": {
3880 "running_image": {
3881 "status": "match",
3882 "evidence": {
3883 "method": "linux_proc_sha256",
3884 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3885 }
3886 }
3887 }
3888 },
3889 {
3890 "module_id": "healthy-b",
3891 "module_declared": { "status": "unverifiable" },
3892 "daemon_observed": {
3893 "running_image": {
3894 "status": "unavailable",
3895 "reason": "unsupported_platform"
3896 }
3897 }
3898 }
3899 ]
3900 });
3901
3902 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3903 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3904 panic!("decoded wrong response variant");
3905 };
3906 assert_eq!(modules.len(), 3);
3907 assert_eq!(modules[0].module_id, "future");
3908 assert_eq!(
3909 modules[0].daemon_observed.running_image,
3910 RunningImageAgreement::Unavailable {
3911 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3912 }
3913 );
3914 assert_eq!(modules[1].module_id, "healthy-a");
3915 assert_eq!(modules[2].module_id, "healthy-b");
3916 }
3917
3918 #[test]
3919 fn tagged_unknown_values_retain_tag_and_body() {
3920 macro_rules! assert_unknown_round_trip {
3921 ($ty:ident, $field:literal, $value:expr) => {
3922 let value = $value;
3923 let wire = serde_json::to_string(&value).unwrap();
3924 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3925 match decoded {
3926 $ty::Unknown { tag, body } => {
3927 assert_eq!(tag, value[$field].as_str().unwrap());
3928 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3929 }
3930 _ => panic!("decoded known variant"),
3931 }
3932 };
3933 }
3934
3935 assert_unknown_round_trip!(
3936 ModuleDeclaredProvenance,
3937 "status",
3938 serde_json::json!({"status": "future", "build": {"version": 7}})
3939 );
3940 assert_unknown_round_trip!(
3941 RunningImageAgreement,
3942 "status",
3943 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3944 );
3945 assert_unknown_round_trip!(
3946 RunningImageEvidence,
3947 "method",
3948 serde_json::json!({"method": "future", "digest": "abc"})
3949 );
3950 assert_unknown_round_trip!(
3951 SupervisorRouteConsumer,
3952 "kind",
3953 serde_json::json!({"kind": "future", "module_id": "m"})
3954 );
3955 assert_unknown_round_trip!(
3956 StderrCaptureState,
3957 "state",
3958 serde_json::json!({"state": "future", "reason": "because"})
3959 );
3960 assert_unknown_round_trip!(
3961 StderrTailEntry,
3962 "kind",
3963 serde_json::json!({"kind": "future", "text": "line"})
3964 );
3965 assert_unknown_round_trip!(
3966 ChildResourceUsage,
3967 "status",
3968 serde_json::json!({"status": "future", "memory_bytes": 1})
3969 );
3970 }
3971
3972 #[test]
3973 fn child_resource_usage_round_trips_both_known_states() {
3974 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3975 memory_bytes: 0,
3976 memory_kind: ChildMemoryKind::ResidentSet,
3977 swap_bytes: Some(0),
3978 cpu_user_ms: 0,
3979 cpu_system_ms: 0,
3980 });
3981 let wire = serde_json::to_value(&measured).unwrap();
3982 assert_eq!(
3983 wire,
3984 serde_json::json!({
3985 "status": "measured",
3986 "memory_bytes": 0,
3987 "memory_kind": "resident_set",
3988 "swap_bytes": 0,
3989 "cpu_user_ms": 0,
3990 "cpu_system_ms": 0
3991 })
3992 );
3993 assert_eq!(
3994 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3995 measured
3996 );
3997
3998 let unavailable = ChildResourceUsage::Unavailable {
3999 reason: ChildResourceUnavailableReason::NotRunning,
4000 };
4001 let wire = serde_json::to_value(&unavailable).unwrap();
4002 assert_eq!(
4003 wire,
4004 serde_json::json!({"status": "unavailable", "reason": "not_running"})
4005 );
4006 assert_eq!(
4007 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4008 unavailable
4009 );
4010 }
4011
4012 #[test]
4013 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
4014 let stamped: StderrTailEntry = serde_json::from_str(
4018 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
4019 )
4020 .unwrap();
4021 assert_eq!(
4022 stamped,
4023 StderrTailEntry::Line {
4024 text: "boom".to_string(),
4025 truncated: true,
4026 at_ms: Some(1_789_801_440_685),
4027 }
4028 );
4029 let unstamped: StderrTailEntry =
4030 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
4031 assert_eq!(
4032 unstamped,
4033 StderrTailEntry::Line {
4034 text: "boom".to_string(),
4035 truncated: false,
4036 at_ms: None,
4037 }
4038 );
4039 assert_eq!(
4042 serde_json::to_string(&unstamped).unwrap(),
4043 r#"{"kind":"line","text":"boom"}"#
4044 );
4045 assert_eq!(
4046 serde_json::to_value(&stamped).unwrap()["at_ms"],
4047 serde_json::json!(1_789_801_440_685u64)
4048 );
4049 }
4050
4051 #[test]
4052 fn tagged_unknown_values_round_trip_the_original_json() {
4053 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
4054 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4055 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4056 }
4057
4058 #[test]
4059 fn tagged_unknown_values_round_trip_trailing_tag() {
4060 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
4061 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4062 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4063
4064 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
4065 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4066 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4067 }
4068
4069 #[test]
4070 fn tagged_unknown_values_round_trip_middle_tag() {
4071 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
4072 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4073 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4074
4075 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
4076 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4077 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4078 }
4079
4080 #[test]
4081 fn tagged_unknown_values_round_trip_deep_payload() {
4082 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
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#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
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_reject_non_object_bodies() {
4093 for wire in ["42", r#""future""#, "[]"] {
4094 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
4095 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
4096 }
4097 }
4098
4099 #[test]
4100 fn duplicate_discriminators_reject_without_panicking() {
4101 assert_eq!(
4102 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
4103 .unwrap(),
4104 ModuleDeclaredProvenance::Unverifiable
4105 );
4106 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
4107 .unwrap()
4108 {
4109 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
4110 _ => panic!("future discriminator decoded as a known variant"),
4111 }
4112
4113 let wires = [
4114 r#"{"status":"reported","status":"unverifiable"}"#,
4115 r#"{"status":"unverifiable","status":"reported"}"#,
4116 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4117 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4118 ];
4119
4120 for wire in wires {
4121 let result =
4122 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4123 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4124 assert!(
4125 result.unwrap().is_err(),
4126 "duplicate discriminator decoded: {wire}"
4127 );
4128 }
4129
4130 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4131 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4132 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4133 assert!(
4134 result.unwrap().is_err(),
4135 "duplicate discriminator decoded: {wire}"
4136 );
4137 }
4138
4139 #[test]
4140 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4141 let known_wire =
4142 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4143 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4144 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4145
4146 for wire in [
4147 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4148 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4149 ] {
4150 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4151 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4152 }
4153
4154 for wire in [
4155 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4156 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4157 ] {
4158 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4159 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4160 }
4161
4162 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4163 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4164 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4165
4166 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4167 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4168 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4169 }
4170
4171 #[test]
4172 fn tagged_unknown_member_does_not_discard_known_siblings() {
4173 let body = serde_json::json!({
4174 "modules": [{
4175 "module_id": "target",
4176 "routes": [
4177 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4178 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4179 ]
4180 }]
4181 });
4182 let decoded: ClientControlResponse = serde_json::from_value(
4183 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4184 )
4185 .unwrap();
4186 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4187 panic!("decoded wrong response variant");
4188 };
4189 assert_eq!(modules[0].routes.len(), 2);
4190 assert_eq!(
4191 modules[0].routes[1].consumer,
4192 SupervisorRouteConsumer::Direct { connection_id: 7 }
4193 );
4194 }
4195}
4196
4197#[cfg(test)]
4198mod launch_nonce_redaction_tests {
4199 use super::*;
4200
4201 const NONCE: &str = "nonce-f00dfeed1234abcd";
4202
4203 fn identity() -> ConsumerIdentity {
4204 ConsumerIdentity {
4205 module_id: "wernicke".to_string(),
4206 launch_nonce: NONCE.to_string(),
4207 }
4208 }
4209
4210 #[test]
4211 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4212 let printed = format!("{:?}", identity());
4213 assert!(printed.contains("wernicke"), "{printed}");
4214 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4215 }
4216
4217 #[test]
4218 fn route_open_request_debug_never_prints_the_nonce() {
4219 let request = ClientControlRequest::RouteOpen {
4220 busy_refusals: None,
4221 target: subc_protocol::RouteTarget::ToolProvider {
4222 module_id: "broca".to_string(),
4223 },
4224 identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4225 consumer_identity: Some(identity()),
4226 consumer_capabilities: None,
4227 role_versions: None,
4228 admission_facts: None,
4229 scope: None,
4230 };
4231 let printed = format!("{request:?}");
4232 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4233 }
4234}
4235
4236#[cfg(test)]
4237mod reader_skew_tests {
4238 use super::*;
4239 use serde_json::{json, Value};
4240
4241 fn catalog() -> Value {
4242 json!({"module_id": "provider", "roles": [], "control_ops": []})
4243 }
4244
4245 fn reply() -> Value {
4246 json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4247 }
4248
4249 fn target() -> Value {
4250 json!({
4251 "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4252 "authority_epoch": 23, "first_party": true,
4253 "approved_declarations_digest": "approved"
4254 })
4255 }
4256
4257 fn request() -> Value {
4258 json!({
4259 "op": "route.open",
4260 "target": {"kind": "tool_provider", "module_id": "provider"},
4261 "identity": {"harness": "test", "session": "session-1"}
4262 })
4263 }
4264
4265 #[test]
4266 fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4267 let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4268 let built = CatalogEntry::new("provider", vec![], vec![]);
4269 assert_eq!(old, built);
4270 assert_eq!(old.first_party, None);
4271 let old_bytes = serde_json::to_value(&old).unwrap();
4272 let additions = json!({
4273 "incarnation": "daemon", "spawn": 17, "first_party": false,
4274 "origin": "development", "requested_declarations_digest": "requested",
4275 "approved_declarations_digest": "approved"
4276 });
4277 let mut body = catalog();
4278 for (key, value) in additions.as_object().unwrap() {
4279 assert!(old_bytes.get(key).is_none(), "{key}");
4280 body[key] = value.clone();
4281 }
4282 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4283 let encoded = serde_json::to_value(&decoded).unwrap();
4284 for (key, value) in additions.as_object().unwrap() {
4285 assert_eq!(&encoded[key], value, "{key}");
4286 }
4287 assert_eq!(decoded.first_party, Some(false));
4288 assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4289 }
4290
4291 #[test]
4292 fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4293 let mut body = catalog();
4294 body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4295 body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4296 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4297 let encoded = serde_json::to_value(decoded).unwrap();
4298 for key in ["requested_declarations", "approved_declarations"] {
4299 assert_eq!(encoded[key], body[key]);
4300 }
4301 let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4302 assert_eq!(unfiltered.approved_declarations, None);
4303 assert_eq!(unfiltered.requested_declarations, None);
4304 }
4305
4306 #[test]
4307 fn reader_skew_catalog_unknown_origin_is_other() {
4308 let mut body = catalog();
4309 body["origin"] = json!("future-origin");
4310 let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4311 assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4312 }
4313
4314 #[test]
4315 fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4316 let mut body = catalog();
4317 body["spawn"] = json!(9_007_199_254_740_991_u64);
4318 let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4319 assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4320 for invalid in [
4321 json!(9_007_199_254_740_992_u64),
4322 json!(-1),
4323 json!(1.5),
4324 json!("17"),
4325 ] {
4326 body["spawn"] = invalid;
4327 assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4328 }
4329 }
4330
4331 #[test]
4332 fn reader_skew_catalog_watch_request_uses_subscription_op() {
4333 let body = json!({"op": "catalog.watch"});
4334 let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4335 assert_eq!(request, CatalogWatchRequest::new());
4336 assert_eq!(serde_json::to_value(request).unwrap(), body);
4337 assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4338 for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4339 assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4340 }
4341 }
4342
4343 #[test]
4344 fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4345 for generation in [0, 19, 42] {
4346 let body = json!({"op": "catalog.watch", "generation": generation});
4347 let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4348 assert_eq!(push, CatalogWatchResponse::new(generation));
4349 assert_eq!(serde_json::to_value(push).unwrap(), body);
4350 }
4351 assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4352 for invalid in [
4353 json!({"op": "catalog.watch"}),
4354 json!({"op": "activity.subscribe", "generation": 1}),
4355 ] {
4356 assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4357 }
4358 }
4359
4360 #[test]
4361 fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4362 let mut body = reply();
4363 let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4364 let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4365 assert_eq!(empty, RouteOpenReplyExt::new());
4366 empty.write_to(&mut body).unwrap();
4367 assert_eq!(body, reply());
4368 body["target"] = target();
4369 let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4370 assert_eq!(
4371 decoded.target.as_ref().unwrap().kind,
4372 RouteOpenTargetKind::Spawn
4373 );
4374 let mut encoded = reply();
4375 RouteOpenReplyExt::new()
4376 .with_target(decoded.target)
4377 .write_to(&mut encoded)
4378 .unwrap();
4379 assert_eq!(encoded, body);
4380 assert_eq!(
4381 serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4382 legacy
4383 );
4384 RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4385 assert_eq!(encoded, reply());
4386 }
4387
4388 #[test]
4389 fn reader_skew_route_open_incomplete_target_is_unmarked() {
4390 let mut body = reply();
4391 body["target"] = target();
4392 assert!(RouteOpenReplyExt::read_from(&body)
4393 .unwrap()
4394 .target
4395 .is_some());
4396 for key in [
4397 "incarnation",
4398 "kind",
4399 "spawn",
4400 "authority_epoch",
4401 "first_party",
4402 "approved_declarations_digest",
4403 ] {
4404 let mut incomplete = body.clone();
4405 incomplete["target"].as_object_mut().unwrap().remove(key);
4406 assert_eq!(
4407 RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4408 None,
4409 "{key}"
4410 );
4411 }
4412 body["target"] = Value::Null;
4413 assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4414 }
4415
4416 #[test]
4417 fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4418 for (kind, expected) in [
4419 ("prefix", RouteOpenTargetKind::Prefix),
4420 ("unsupervised", RouteOpenTargetKind::Unsupervised),
4421 ] {
4422 let mut body = reply();
4423 body["target"] = target();
4424 body["target"]["kind"] = json!(kind);
4425 body["target"]["spawn"] = json!("not-a-spawn");
4427 body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4428 body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4429 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4430 let target = ext.target.as_ref().unwrap();
4431 assert_eq!(target.kind, expected);
4432 assert_eq!(target.spawn, None);
4433 assert_eq!(target.authority_epoch, None);
4434 assert_eq!(target.approved_declarations_digest, None);
4435 assert!(!target.first_party);
4436 let mut encoded = reply();
4437 ext.write_to(&mut encoded).unwrap();
4438 for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
4439 assert!(encoded["target"].get(key).is_none());
4440 }
4441 }
4442 }
4443
4444 #[test]
4445 fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4446 let mut body = reply();
4447 body["target"] = target();
4448 body["target"]["kind"] = json!("future-kind");
4449 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4450 let target = ext.target.unwrap();
4451 assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4452 assert_eq!(target.spawn, None);
4453 assert_eq!(target.authority_epoch, None);
4454 assert_eq!(target.approved_declarations_digest, None);
4455 assert!(!target.first_party);
4456 }
4457
4458 #[test]
4459 fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4460 for field in ["spawn", "authority_epoch"] {
4461 let mut body = reply();
4462 body["target"] = target();
4463 body["target"][field] = json!(9_007_199_254_740_991_u64);
4464 let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4465 assert_eq!(
4466 serde_json::to_value(ext).unwrap()["target"][field],
4467 9_007_199_254_740_991_u64
4468 );
4469 for invalid in [
4470 json!(9_007_199_254_740_992_u64),
4471 json!(-1),
4472 json!(1.5),
4473 json!("17"),
4474 ] {
4475 body["target"][field] = invalid;
4476 assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4477 let mut incomplete = body.clone();
4478 incomplete["target"]
4479 .as_object_mut()
4480 .unwrap()
4481 .remove("incarnation");
4482 assert!(
4483 RouteOpenReplyExt::read_from(&incomplete).is_err(),
4484 "{field}"
4485 );
4486 }
4487 }
4488 }
4489
4490 #[test]
4491 fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4492 let mut body = request();
4493 let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4494 assert_eq!(
4495 RouteOpenRequestExt::read_from(&body).unwrap(),
4496 RouteOpenRequestExt::new()
4497 );
4498 RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4499 assert_eq!(body, request());
4500 body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4501 let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4502 assert_eq!(
4503 decoded.accepts_close_reasons,
4504 Some(vec!["authority_changed".into(), "future-reason".into()])
4505 );
4506 let mut encoded = request();
4507 RouteOpenRequestExt::new()
4508 .with_accepts_close_reasons(decoded.accepts_close_reasons)
4509 .write_to(&mut encoded)
4510 .unwrap();
4511 assert_eq!(encoded, body);
4512 assert_eq!(
4513 serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4514 legacy
4515 );
4516 RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4517 assert_eq!(encoded, request());
4518 assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4519 }
4520
4521 #[test]
4522 fn reader_skew_route_open_helpers_refuse_other_bodies() {
4523 for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4524 assert!(RouteOpenRequestExt::read_from(&body).is_err());
4525 assert!(RouteOpenReplyExt::read_from(&body).is_err());
4526 assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4527 assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4528 }
4529 }
4530
4531 #[test]
4532 fn reader_skew_route_open_target_constructor_validates_like_reader() {
4533 let spawn = RouteOpenTarget::new(
4534 "daemon",
4535 RouteOpenTargetKind::Spawn,
4536 Some(17),
4537 Some(23),
4538 true,
4539 Some("approved".into()),
4540 )
4541 .unwrap();
4542 assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4543 for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4544 assert!(RouteOpenTarget::new(
4545 "daemon",
4546 RouteOpenTargetKind::Spawn,
4547 Some(spawn),
4548 Some(epoch),
4549 true,
4550 Some("approved".into())
4551 )
4552 .is_err());
4553 }
4554 }
4555}
4556
4557#[cfg(test)]
4558mod claim_wire_tests {
4559 use super::*;
4560 use serde_json::{json, Value};
4561
4562 fn legacy_provenance() -> SupervisorModuleProvenance {
4563 SupervisorModuleProvenance {
4564 module_id: "worker".into(),
4565 module_declared: ModuleDeclaredProvenance::Unverifiable,
4566 daemon_observed: SupervisorObservedProcess {
4567 launch_nonce_source: None,
4568 pid: None,
4569 spawned_at_ms: None,
4570 spawned_from: None,
4571 running_image: RunningImageAgreement::Unavailable {
4572 reason: RunningImageUnavailableReason::NotRunning,
4573 },
4574 },
4575 }
4576 }
4577
4578 #[test]
4579 fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4580 let legacy = legacy_provenance();
4581 let original = serde_json::to_value(&legacy).unwrap();
4582 let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4583 assert_eq!(absent.registration, None);
4584 let mut wire = original.clone();
4585 absent.write_to(&mut wire).unwrap();
4586 assert_eq!(wire, original);
4587 for (method, spelling) in [
4588 (RegistrationMethod::Channel, "channel"),
4589 (RegistrationMethod::Nonce, "nonce"),
4590 ] {
4591 let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4592 ext.write_to(&mut wire).unwrap();
4593 assert_eq!(wire["registration"], spelling);
4594 assert_eq!(
4595 SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4596 ext
4597 );
4598 let old_reader: SupervisorModuleProvenance =
4599 serde_json::from_value(wire.clone()).unwrap();
4600 assert_eq!(old_reader, legacy);
4601 assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4602 }
4603 absent.write_to(&mut wire).unwrap();
4604 assert_eq!(wire, original);
4605 for mut invalid in [Value::Null, json!([]), json!("entry")] {
4606 assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4607 assert!(absent.write_to(&mut invalid).is_err());
4608 }
4609 }
4610
4611 #[test]
4612 fn provenance_unknown_registration_is_not_channel_or_nonce() {
4613 let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4614 wire["registration"] = json!("future_method");
4615 let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4616 assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4617 assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4618 assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4619 wire["registration"] = json!(false);
4620 assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4621 }
4622
4623 #[test]
4624 fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4625 let original = serde_json::to_value(legacy_provenance()).unwrap();
4626 for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4627 let mut golden = original.clone();
4628 golden["registration_declaration"] = json!(declaration);
4629 let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4630 assert_eq!(
4631 serde_json::to_value(&extension).unwrap(),
4632 json!({
4633 "registration_declaration": declaration
4634 })
4635 );
4636 let mut written = original.clone();
4637 extension.write_to(&mut written).unwrap();
4638 assert_eq!(written, golden);
4639 assert_eq!(
4640 serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4641 legacy_provenance()
4642 );
4643 SupervisorModuleProvenanceExt::new()
4644 .write_to(&mut written)
4645 .unwrap();
4646 assert_eq!(written, original);
4647 }
4648 }
4649
4650 #[test]
4651 fn admission_refusal_is_optional_and_open() {
4652 let entry = SupervisorEntry::new(
4653 "worker",
4654 "stopped",
4655 true,
4656 false,
4657 SupervisorHealthStatus::Unknown,
4658 );
4659 let original = serde_json::to_value(&entry).unwrap();
4660 assert!(original.get("admission_refused").is_none());
4661 let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
4662 assert_eq!(read.admission_refused, None);
4663 assert_eq!(serde_json::to_value(read).unwrap(), original);
4664 assert_eq!(
4665 REGISTRATION_CHANNEL_UNSUPPORTED,
4666 "registration_channel_unsupported"
4667 );
4668 for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
4669 let mut wire = original.clone();
4670 wire["admission_refused"] = json!(reason);
4671 let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
4672 assert_eq!(read.admission_refused.as_deref(), Some(reason));
4673 assert_eq!(serde_json::to_value(read).unwrap(), wire);
4674 let built = entry.clone().with_admission_refused(Some(reason.into()));
4675 assert_eq!(serde_json::to_value(built).unwrap(), wire);
4676 }
4677 }
4678}