1use std::collections::BTreeMap;
9
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13use crate::{
14 call_mode::CallMode,
15 manifest::{CapabilityDeclarations, ProviderRole},
16 scope::{
17 ScopeEnd, ScopeEndResult, ScopeEnded, ScopeRecord, ScopeRecordResult, ScopeStamp,
18 ScopeStatus,
19 },
20 BindIdentity, Principal, RouteCloseReason, RouteTarget,
21};
22
23pub const MODULE_CONTROL_OP_HEALTH_CHECK: &str = "health.check";
24pub const MODULE_TO_SUBC_OP_CATALOG_UPDATE: &str = "catalog.update";
25pub const MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS: &str =
26 "catalog.update_role_declarations";
27
28#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
29#[serde(rename_all = "snake_case")]
30pub enum HealthStatus {
31 Ok,
32 Degraded,
33 Failing,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
37pub struct HealthReport {
38 pub status: HealthStatus,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub detail: Option<String>,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub metrics: Option<Value>,
43}
44
45impl HealthReport {
46 pub fn ok() -> Self {
47 Self {
48 status: HealthStatus::Ok,
49 detail: None,
50 metrics: None,
51 }
52 }
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
57#[serde(tag = "op")]
58#[allow(clippy::large_enum_variant)]
61pub enum ModuleControlRequest {
62 #[serde(rename = "route.bind")]
63 RouteBind {
64 route_channel: u16,
65 epoch: u32,
66 target: RouteTarget,
67 identity: BindIdentity,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
82 principal: Option<Principal>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
92 consumer_capabilities: Option<Vec<String>>,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
102 role_versions: Option<BTreeMap<String, String>>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
105 admission_facts: Option<Value>,
106 #[serde(default, skip_serializing_if = "Option::is_none")]
116 scope: Option<ScopeStamp>,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
122 call_mode: Option<CallMode>,
123 },
124 #[serde(rename = "health.check")]
125 HealthCheck {},
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
130#[serde(tag = "op")]
131pub enum ModuleControlCommand {
132 #[serde(rename = "module.draining")]
133 Draining {
134 reason: RouteCloseReason,
135 deadline_ms: u64,
151 },
152 #[serde(rename = "module.upgrading")]
154 Upgrading {
155 reconnect_by_ms: u64,
158 },
159}
160
161pub const LIVE_UPGRADE_CAPABILITY: &str = "live-upgrade/v1";
163
164pub const ACCEPTING_DRAIN_CAPABILITY: &str = "accepting-drain/v1";
166
167pub const MODULE_DRAIN_READY_OP: &str = "module.drain_ready";
169
170#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
172#[serde(tag = "op", deny_unknown_fields)]
173pub enum ModuleDrainReady {
174 #[serde(rename = "module.drain_ready")]
175 Ready {},
176}
177
178#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
180#[serde(tag = "op")]
181pub enum AcceptingDrainCommand {
182 #[serde(rename = "module.draining")]
183 Draining {
184 reason: RouteCloseReason,
185 deadline_ms: u64,
187 accepting: bool,
188 },
189}
190
191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
193#[serde(tag = "op")]
194pub enum ModuleControlResponse {
195 #[serde(rename = "route.bind")]
197 RouteBindAck {},
198 #[serde(rename = "health.check")]
199 HealthCheck {
200 status: HealthStatus,
201 #[serde(default, skip_serializing_if = "Option::is_none")]
202 detail: Option<String>,
203 #[serde(default, skip_serializing_if = "Option::is_none")]
204 metrics: Option<Value>,
205 },
206}
207
208#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
214#[serde(tag = "op")]
215#[non_exhaustive]
216pub enum ModuleControlRequestFromModule {
217 #[serde(rename = "route.authorize")]
219 RouteAuthorize {
220 principal: Principal,
221 scope: crate::scope::RouteAuthorizeScope,
222 target: String,
223 expected: crate::scope::RouteAuthorizeExpected,
224 },
225 #[serde(rename = "catalog.update")]
226 CatalogUpdate {
227 provides: Vec<ProviderRole>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
232 capabilities: Option<CapabilityDeclarations>,
233 #[serde(default, skip_serializing_if = "Option::is_none")]
238 ready: Option<bool>,
239 },
240 #[serde(rename = "catalog.update_role_declarations")]
242 CatalogUpdateRoleDeclarations {
243 #[serde(deserialize_with = "Value::deserialize")]
246 role_declarations: Value,
247 },
248 #[serde(rename = "supervisor.live_roots")]
249 LiveRoots {},
250 #[serde(rename = "policy_root.get")]
251 PolicyRoot(crate::policy_root::GetPolicyRoot),
252 #[serde(rename = "policy_root.rotate")]
253 PolicyRootRotate(crate::policy_root::RotatePolicyRoot),
254 #[serde(rename = "supervisor.agent_commands")]
259 AgentCommands {
260 started: Vec<AgentCommandRoot>,
261 finished: Vec<AgentCommandFinished>,
262 #[serde(default, skip_serializing_if = "Option::is_none")]
263 known: Option<Vec<AgentCommandRoot>>,
264 },
265 #[serde(rename = "scope.sync")]
271 ScopeSync {
272 generation: u64,
273 scopes: Vec<ScopeRecord>,
274 },
275 #[serde(rename = "scope.apply")]
280 ScopeApply {
281 generation: u64,
282 upsert: Vec<ScopeRecord>,
283 end: Vec<ScopeEnd>,
284 },
285 #[serde(rename = "scope.describe")]
287 ScopeDescribe {
288 owner: Principal,
289 #[serde(rename = "ref")]
290 scope_ref: String,
291 },
292}
293
294#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
297pub struct AgentCommandRoot {
298 pub pid: u32,
299 pub start_time_ms: u64,
300}
301
302#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
304pub struct AgentCommandFinished {
305 pub pid: u32,
306 pub start_time_ms: u64,
307 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub cpu_ms: Option<u64>,
309}
310
311#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
313pub struct LiveRoot {
314 pub project_root: std::path::PathBuf,
315 pub bound: u64,
316 pub pending: u64,
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
321#[serde(tag = "op")]
322#[allow(clippy::large_enum_variant)]
325pub enum ModuleControlResponseToModule {
326 #[serde(rename = "catalog.update")]
327 CatalogUpdate {},
328 #[serde(rename = "catalog.update_role_declarations")]
329 CatalogUpdateRoleDeclarations {},
330 #[serde(rename = "supervisor.live_roots")]
331 LiveRoots {
332 roots: Vec<LiveRoot>,
333 unknown_root_bindings: u64,
334 total_bindings: u64,
335 },
336 #[serde(rename = "policy_root.get")]
337 PolicyRoot(crate::policy_root::PolicyRoot),
338 #[serde(rename = "policy_root.rotate")]
339 PolicyRootRotate(crate::policy_root::PolicyRootChange),
340 #[serde(rename = "scope.sync")]
341 ScopeSync {
342 generation: u64,
343 results: Vec<ScopeRecordResult>,
344 #[serde(default, skip_serializing_if = "Vec::is_empty")]
345 ended: Vec<ScopeEnded>,
346 },
347 #[serde(rename = "scope.apply")]
348 ScopeApply {
349 generation: u64,
350 results: Vec<ScopeRecordResult>,
351 end_results: Vec<ScopeEndResult>,
352 #[serde(default, skip_serializing_if = "Vec::is_empty")]
353 ended: Vec<ScopeEnded>,
354 },
355 #[serde(rename = "scope.describe")]
356 ScopeDescribe {
357 status: ScopeStatus,
358 #[serde(default, skip_serializing_if = "Option::is_none")]
360 scope_epoch: Option<u64>,
361 daemon_incarnation: String,
362 owner_synced: bool,
364 owner_configured: bool,
366 #[serde(default, skip_serializing_if = "Option::is_none")]
368 scope: Option<ScopeStamp>,
369 },
370}
371
372#[non_exhaustive]
378#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
379pub struct OperatorConfirmRequest {
380 op: OperatorConfirmOp,
381 pub summary: String,
382 pub route_channel: u16,
384 pub route_epoch: u32,
386 #[serde(default, skip_serializing_if = "Option::is_none")]
391 pub kind: Option<OperatorConfirmKind>,
392 #[serde(default, skip_serializing_if = "Option::is_none")]
396 pub operation: Option<String>,
397}
398
399impl OperatorConfirmRequest {
400 pub fn new(summary: impl Into<String>, route_channel: u16, route_epoch: u32) -> Self {
403 Self {
404 op: OperatorConfirmOp::Confirm,
405 summary: summary.into(),
406 route_channel,
407 route_epoch,
408 kind: None,
409 operation: None,
410 }
411 }
412
413 #[must_use]
415 pub fn with_kind(mut self, kind: Option<OperatorConfirmKind>) -> Self {
416 self.kind = kind;
417 self
418 }
419
420 #[must_use]
422 pub fn with_operation(mut self, operation: Option<String>) -> Self {
423 self.operation = operation;
424 self
425 }
426}
427
428#[derive(Debug, Clone, PartialEq, Eq)]
434pub enum OperatorConfirmKind {
435 Operation,
437 Enrollment,
439 Unknown(String),
440}
441
442impl Serialize for OperatorConfirmKind {
443 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
444 serializer.serialize_str(match self {
445 Self::Operation => "operation",
446 Self::Enrollment => "enrollment",
447 Self::Unknown(value) => value,
448 })
449 }
450}
451
452impl<'de> Deserialize<'de> for OperatorConfirmKind {
453 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
454 Ok(match String::deserialize(deserializer)?.as_str() {
455 "operation" => Self::Operation,
456 "enrollment" => Self::Enrollment,
457 value => Self::Unknown(value.to_owned()),
458 })
459 }
460}
461
462#[non_exhaustive]
467#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
468pub struct OperatorConfirmReply {
469 op: OperatorConfirmOp,
470 pub outcome: String,
471}
472
473impl OperatorConfirmReply {
474 pub fn confirmed() -> Self {
475 Self {
476 op: OperatorConfirmOp::Confirm,
477 outcome: "confirmed".to_string(),
478 }
479 }
480}
481
482#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
485enum OperatorConfirmOp {
486 #[serde(rename = "operator.confirm")]
487 Confirm,
488}
489
490impl From<HealthReport> for ModuleControlResponse {
491 fn from(report: HealthReport) -> Self {
492 Self::HealthCheck {
493 status: report.status,
494 detail: report.detail,
495 metrics: report.metrics,
496 }
497 }
498}
499
500impl ModuleControlResponse {
501 pub fn health_report(&self) -> Option<HealthReport> {
502 match self {
503 Self::HealthCheck {
504 status,
505 detail,
506 metrics,
507 } => Some(HealthReport {
508 status: *status,
509 detail: detail.clone(),
510 metrics: metrics.clone(),
511 }),
512 Self::RouteBindAck {} => None,
513 }
514 }
515}
516
517#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
519#[serde(tag = "op")]
520pub enum ModuleControlPush {
521 #[serde(rename = "route.status")]
522 RouteStatus {
523 route_channel: u16,
524 route_epoch: u32,
525 status: String,
526 },
527}
528
529pub const ROLE_VERSIONS_FIELD: &str = "role_versions";
533
534pub const MAX_ROLE_VERSIONS: usize = 8;
536
537pub const MAX_ROLE_NAME_LEN: usize = 64;
539
540#[derive(Clone, Debug, PartialEq, Eq)]
542#[non_exhaustive]
543pub enum RoleVersionsError {
544 TooMany { count: usize },
546 InvalidRole { role: String },
550 InvalidVersion { role: String, version: String },
553}
554
555impl RoleVersionsError {
556 pub fn field(&self) -> &'static str {
558 ROLE_VERSIONS_FIELD
559 }
560}
561
562impl std::fmt::Display for RoleVersionsError {
563 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
564 match self {
565 Self::TooMany { count } => write!(
566 f,
567 "{ROLE_VERSIONS_FIELD} has {count} entries; at most {MAX_ROLE_VERSIONS} are allowed"
568 ),
569 Self::InvalidRole { role } => write!(
570 f,
571 "{ROLE_VERSIONS_FIELD} names role {role:?}, which is not lowercase letters and \
572 digits in words joined by '-', at most {MAX_ROLE_NAME_LEN} bytes"
573 ),
574 Self::InvalidVersion { role, version } => write!(
575 f,
576 "{ROLE_VERSIONS_FIELD} gives role {role:?} version {version:?}, which is not 'v' \
577 followed by a positive integer without leading zeros"
578 ),
579 }
580 }
581}
582
583impl std::error::Error for RoleVersionsError {}
584
585pub fn validate_role_versions(
593 role_versions: &BTreeMap<String, String>,
594) -> Result<(), RoleVersionsError> {
595 if role_versions.len() > MAX_ROLE_VERSIONS {
596 return Err(RoleVersionsError::TooMany {
597 count: role_versions.len(),
598 });
599 }
600 for (role, version) in role_versions {
601 if !is_role_name(role) {
602 return Err(RoleVersionsError::InvalidRole { role: role.clone() });
603 }
604 if !is_role_version(version) {
605 return Err(RoleVersionsError::InvalidVersion {
606 role: role.clone(),
607 version: version.clone(),
608 });
609 }
610 }
611 Ok(())
612}
613
614fn is_role_name(role: &str) -> bool {
615 !role.is_empty()
616 && role.len() <= MAX_ROLE_NAME_LEN
617 && role.split('-').all(|word| {
618 !word.is_empty()
619 && word
620 .bytes()
621 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
622 })
623}
624
625fn is_role_version(version: &str) -> bool {
626 let bytes = version.as_bytes();
627 bytes.len() >= 2
628 && bytes[0] == b'v'
629 && (b'1'..=b'9').contains(&bytes[1])
630 && bytes[2..].iter().all(u8::is_ascii_digit)
631}
632
633#[cfg(test)]
634mod tests {
635 use super::*;
636
637 #[test]
638 fn accepting_drain_wire_bodies_are_additive() {
639 let wire = br#"{"op":"module.drain_ready"}"#;
640 assert_eq!(
641 serde_json::to_vec(&ModuleDrainReady::Ready {}).unwrap(),
642 wire
643 );
644 assert_eq!(
645 serde_json::from_slice::<ModuleDrainReady>(wire).unwrap(),
646 ModuleDrainReady::Ready {}
647 );
648 assert!(serde_json::from_slice::<ModuleDrainReady>(
649 br#"{"op":"module.drain_ready","module_id":"other"}"#
650 )
651 .is_err());
652 let accepting = AcceptingDrainCommand::Draining {
653 reason: RouteCloseReason::Restart,
654 deadline_ms: 1000,
655 accepting: true,
656 };
657 let notice = serde_json::to_vec(&accepting).unwrap();
658 assert_eq!(
659 notice,
660 br#"{"op":"module.draining","reason":"restart","deadline_ms":1000,"accepting":true}"#
661 );
662 let legacy = ModuleControlCommand::Draining {
663 reason: RouteCloseReason::Restart,
664 deadline_ms: 1000,
665 };
666 assert_eq!(
667 serde_json::from_slice::<ModuleControlCommand>(¬ice).unwrap(),
668 legacy
669 );
670 assert_eq!(
671 serde_json::to_vec(&legacy).unwrap(),
672 br#"{"op":"module.draining","reason":"restart","deadline_ms":1000}"#
673 );
674 }
675 #[test]
676 fn catalog_update_role_declarations_wire_round_trip() {
677 for declarations in [
678 serde_json::json!({"media-provider/v1": {"engines": ["image"]}}),
679 serde_json::json!({}),
680 ] {
681 let body = serde_json::json!({
682 "op": "catalog.update_role_declarations",
683 "role_declarations": declarations,
684 });
685 let request: ModuleControlRequestFromModule =
686 serde_json::from_value(body.clone()).unwrap();
687 assert_eq!(serde_json::to_value(request).unwrap(), body);
688 }
689 let body = serde_json::json!({"op": "catalog.update_role_declarations"});
690 let response: ModuleControlResponseToModule = serde_json::from_value(body.clone()).unwrap();
691 assert_eq!(serde_json::to_value(response).unwrap(), body);
692 assert!(serde_json::from_value::<ModuleControlRequestFromModule>(body).is_err());
693 }
694
695 fn map(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
696 entries
697 .iter()
698 .map(|(role, version)| (role.to_string(), version.to_string()))
699 .collect()
700 }
701
702 #[test]
703 fn role_versions_accept_role_names_and_positive_versions() {
704 for entries in [
705 vec![],
706 vec![("tool-provider", "v1")],
707 vec![("a", "v9"), ("b2", "v10"), ("x-1-y", "v1203")],
708 ] {
709 assert_eq!(
710 validate_role_versions(&map(&entries)),
711 Ok(()),
712 "{entries:?}"
713 );
714 }
715 let longest = "a".repeat(MAX_ROLE_NAME_LEN);
716 assert_eq!(validate_role_versions(&map(&[(&longest, "v1")])), Ok(()));
717 let full: BTreeMap<String, String> = (0..MAX_ROLE_VERSIONS)
718 .map(|index| (format!("role-{index}"), "v1".to_string()))
719 .collect();
720 assert_eq!(validate_role_versions(&full), Ok(()));
721 }
722
723 #[test]
724 fn role_versions_refuse_malformed_role_names() {
725 let too_long = "a".repeat(MAX_ROLE_NAME_LEN + 1);
726 for role in [
727 "",
728 "Tool-provider",
729 "tool_provider",
730 "tool provider",
731 "-tool",
732 "tool-",
733 "tool--provider",
734 "tool.provider",
735 "outil-é",
736 too_long.as_str(),
737 ] {
738 let error = validate_role_versions(&map(&[(role, "v1")])).unwrap_err();
739 assert_eq!(
740 error,
741 RoleVersionsError::InvalidRole {
742 role: role.to_string()
743 },
744 "{role:?}"
745 );
746 assert_eq!(error.field(), "role_versions");
747 }
748 }
749
750 #[test]
751 fn role_versions_refuse_malformed_versions() {
752 for version in [
753 "", "v", "v0", "v01", "1", "V1", "v1.0", "v-1", "v1 ", " v1", "vx",
754 ] {
755 let error = validate_role_versions(&map(&[("tool-provider", version)])).unwrap_err();
756 assert_eq!(
757 error,
758 RoleVersionsError::InvalidVersion {
759 role: "tool-provider".to_string(),
760 version: version.to_string(),
761 },
762 "{version:?}"
763 );
764 assert_eq!(error.field(), "role_versions");
765 }
766 }
767
768 #[test]
769 fn role_versions_refuse_more_than_eight_entries() {
770 let nine: BTreeMap<String, String> = (0..=MAX_ROLE_VERSIONS)
771 .map(|index| (format!("role-{index}"), "v1".to_string()))
772 .collect();
773 let error = validate_role_versions(&nine).unwrap_err();
774 assert_eq!(error, RoleVersionsError::TooMany { count: 9 });
775 assert_eq!(error.field(), "role_versions");
776 assert!(error.to_string().starts_with("role_versions"), "{error}");
777 }
778
779 #[test]
780 fn route_bind_omits_absent_role_versions_and_carries_present_ones_verbatim() {
781 let bind = |role_versions| ModuleControlRequest::RouteBind {
782 route_channel: 1,
783 epoch: 1,
784 target: crate::RouteTarget::ToolProvider {
785 module_id: "aft".to_string(),
786 },
787 identity: crate::BindIdentity::new("h", "s"),
788 principal: None,
789 consumer_capabilities: None,
790 role_versions,
791 admission_facts: None,
792 scope: None,
793 call_mode: None,
794 };
795 let absent = serde_json::to_value(bind(None)).unwrap();
796 assert!(absent.get("role_versions").is_none(), "{absent}");
797 let present = bind(Some(map(&[("tool-provider", "v1")])));
798 let encoded = serde_json::to_value(&present).unwrap();
799 assert_eq!(
800 encoded["role_versions"],
801 serde_json::json!({ "tool-provider": "v1" })
802 );
803 let decoded: ModuleControlRequest = serde_json::from_value(encoded).unwrap();
804 assert_eq!(decoded, present);
805 }
806}
807
808#[cfg(test)]
809mod agent_command_tests {
810 use super::*;
811
812 #[test]
813 fn agent_commands_round_trip_start_finish_and_known_snapshot() {
814 let root = AgentCommandRoot {
815 pid: 42,
816 start_time_ms: 1_700_000_000_123,
817 };
818 let request = ModuleControlRequestFromModule::AgentCommands {
819 started: vec![root],
820 finished: vec![AgentCommandFinished {
821 pid: 43,
822 start_time_ms: root.start_time_ms,
823 cpu_ms: Some(100),
824 }],
825 known: Some(vec![root]),
826 };
827 let value = serde_json::to_value(&request).unwrap();
828 assert_eq!(
829 value,
830 serde_json::json!({"op":"supervisor.agent_commands",
831 "started":[{"pid":42,"start_time_ms":1_700_000_000_123_u64}],
832 "finished":[{"pid":43,"start_time_ms":1_700_000_000_123_u64,"cpu_ms":100}],
833 "known":[{"pid":42,"start_time_ms":1_700_000_000_123_u64}]})
834 );
835 assert_eq!(
836 serde_json::from_value::<ModuleControlRequestFromModule>(value).unwrap(),
837 request
838 );
839 let absent = ModuleControlRequestFromModule::AgentCommands {
840 started: Vec::new(),
841 finished: vec![AgentCommandFinished {
842 pid: 1,
843 start_time_ms: 2,
844 cpu_ms: None,
845 }],
846 known: None,
847 };
848 assert_eq!(
849 serde_json::to_value(absent).unwrap(),
850 serde_json::json!({"op":"supervisor.agent_commands",
851 "started":[],"finished":[{"pid":1,"start_time_ms":2}]})
852 );
853 }
854}