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";
25
26#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
27#[serde(rename_all = "snake_case")]
28pub enum HealthStatus {
29 Ok,
30 Degraded,
31 Failing,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
35pub struct HealthReport {
36 pub status: HealthStatus,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub detail: Option<String>,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub metrics: Option<Value>,
41}
42
43impl HealthReport {
44 pub fn ok() -> Self {
45 Self {
46 status: HealthStatus::Ok,
47 detail: None,
48 metrics: None,
49 }
50 }
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
55#[serde(tag = "op")]
56#[allow(clippy::large_enum_variant)]
59pub enum ModuleControlRequest {
60 #[serde(rename = "route.bind")]
61 RouteBind {
62 route_channel: u16,
63 epoch: u32,
64 target: RouteTarget,
65 identity: BindIdentity,
66 #[serde(default, skip_serializing_if = "Option::is_none")]
80 principal: Option<Principal>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
90 consumer_capabilities: Option<Vec<String>>,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
100 role_versions: Option<BTreeMap<String, String>>,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
103 admission_facts: Option<Value>,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
114 scope: Option<ScopeStamp>,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
120 call_mode: Option<CallMode>,
121 },
122 #[serde(rename = "health.check")]
123 HealthCheck {},
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
128#[serde(tag = "op")]
129pub enum ModuleControlCommand {
130 #[serde(rename = "module.draining")]
131 Draining {
132 reason: RouteCloseReason,
133 deadline_ms: u64,
149 },
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
154#[serde(tag = "op")]
155pub enum ModuleControlResponse {
156 #[serde(rename = "route.bind")]
158 RouteBindAck {},
159 #[serde(rename = "health.check")]
160 HealthCheck {
161 status: HealthStatus,
162 #[serde(default, skip_serializing_if = "Option::is_none")]
163 detail: Option<String>,
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 metrics: Option<Value>,
166 },
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
175#[serde(tag = "op")]
176pub enum ModuleControlRequestFromModule {
177 #[serde(rename = "catalog.update")]
178 CatalogUpdate {
179 provides: Vec<ProviderRole>,
180 #[serde(default, skip_serializing_if = "Option::is_none")]
184 capabilities: Option<CapabilityDeclarations>,
185 #[serde(default, skip_serializing_if = "Option::is_none")]
190 ready: Option<bool>,
191 },
192 #[serde(rename = "supervisor.live_roots")]
193 LiveRoots {},
194 #[serde(rename = "scope.sync")]
200 ScopeSync {
201 generation: u64,
202 scopes: Vec<ScopeRecord>,
203 },
204 #[serde(rename = "scope.apply")]
209 ScopeApply {
210 generation: u64,
211 upsert: Vec<ScopeRecord>,
212 end: Vec<ScopeEnd>,
213 },
214 #[serde(rename = "scope.describe")]
216 ScopeDescribe {
217 owner: Principal,
218 #[serde(rename = "ref")]
219 scope_ref: String,
220 },
221}
222
223#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
225pub struct LiveRoot {
226 pub project_root: std::path::PathBuf,
227 pub bound: u64,
228 pub pending: u64,
229}
230
231#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
233#[serde(tag = "op")]
234#[allow(clippy::large_enum_variant)]
237pub enum ModuleControlResponseToModule {
238 #[serde(rename = "catalog.update")]
239 CatalogUpdate {},
240 #[serde(rename = "supervisor.live_roots")]
241 LiveRoots {
242 roots: Vec<LiveRoot>,
243 unknown_root_bindings: u64,
244 total_bindings: u64,
245 },
246 #[serde(rename = "scope.sync")]
247 ScopeSync {
248 generation: u64,
249 results: Vec<ScopeRecordResult>,
250 #[serde(default, skip_serializing_if = "Vec::is_empty")]
251 ended: Vec<ScopeEnded>,
252 },
253 #[serde(rename = "scope.apply")]
254 ScopeApply {
255 generation: u64,
256 results: Vec<ScopeRecordResult>,
257 end_results: Vec<ScopeEndResult>,
258 #[serde(default, skip_serializing_if = "Vec::is_empty")]
259 ended: Vec<ScopeEnded>,
260 },
261 #[serde(rename = "scope.describe")]
262 ScopeDescribe {
263 status: ScopeStatus,
264 #[serde(default, skip_serializing_if = "Option::is_none")]
266 scope_epoch: Option<u64>,
267 daemon_incarnation: String,
268 owner_synced: bool,
270 owner_configured: bool,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
274 scope: Option<ScopeStamp>,
275 },
276}
277
278#[non_exhaustive]
284#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
285pub struct OperatorConfirmRequest {
286 op: OperatorConfirmOp,
287 pub summary: String,
288 pub route_channel: u16,
290 pub route_epoch: u32,
292 #[serde(default, skip_serializing_if = "Option::is_none")]
297 pub kind: Option<OperatorConfirmKind>,
298 #[serde(default, skip_serializing_if = "Option::is_none")]
302 pub operation: Option<String>,
303}
304
305impl OperatorConfirmRequest {
306 pub fn new(summary: impl Into<String>, route_channel: u16, route_epoch: u32) -> Self {
309 Self {
310 op: OperatorConfirmOp::Confirm,
311 summary: summary.into(),
312 route_channel,
313 route_epoch,
314 kind: None,
315 operation: None,
316 }
317 }
318
319 #[must_use]
321 pub fn with_kind(mut self, kind: Option<OperatorConfirmKind>) -> Self {
322 self.kind = kind;
323 self
324 }
325
326 #[must_use]
328 pub fn with_operation(mut self, operation: Option<String>) -> Self {
329 self.operation = operation;
330 self
331 }
332}
333
334#[derive(Debug, Clone, PartialEq, Eq)]
340pub enum OperatorConfirmKind {
341 Operation,
343 Enrollment,
345 Unknown(String),
346}
347
348impl Serialize for OperatorConfirmKind {
349 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
350 serializer.serialize_str(match self {
351 Self::Operation => "operation",
352 Self::Enrollment => "enrollment",
353 Self::Unknown(value) => value,
354 })
355 }
356}
357
358impl<'de> Deserialize<'de> for OperatorConfirmKind {
359 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
360 Ok(match String::deserialize(deserializer)?.as_str() {
361 "operation" => Self::Operation,
362 "enrollment" => Self::Enrollment,
363 value => Self::Unknown(value.to_owned()),
364 })
365 }
366}
367
368#[non_exhaustive]
373#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
374pub struct OperatorConfirmReply {
375 op: OperatorConfirmOp,
376 pub outcome: String,
377}
378
379impl OperatorConfirmReply {
380 pub fn confirmed() -> Self {
381 Self {
382 op: OperatorConfirmOp::Confirm,
383 outcome: "confirmed".to_string(),
384 }
385 }
386}
387
388#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
391enum OperatorConfirmOp {
392 #[serde(rename = "operator.confirm")]
393 Confirm,
394}
395
396impl From<HealthReport> for ModuleControlResponse {
397 fn from(report: HealthReport) -> Self {
398 Self::HealthCheck {
399 status: report.status,
400 detail: report.detail,
401 metrics: report.metrics,
402 }
403 }
404}
405
406impl ModuleControlResponse {
407 pub fn health_report(&self) -> Option<HealthReport> {
408 match self {
409 Self::HealthCheck {
410 status,
411 detail,
412 metrics,
413 } => Some(HealthReport {
414 status: *status,
415 detail: detail.clone(),
416 metrics: metrics.clone(),
417 }),
418 Self::RouteBindAck {} => None,
419 }
420 }
421}
422
423#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
425#[serde(tag = "op")]
426pub enum ModuleControlPush {
427 #[serde(rename = "route.status")]
428 RouteStatus {
429 route_channel: u16,
430 route_epoch: u32,
431 status: String,
432 },
433}
434
435pub const ROLE_VERSIONS_FIELD: &str = "role_versions";
439
440pub const MAX_ROLE_VERSIONS: usize = 8;
442
443pub const MAX_ROLE_NAME_LEN: usize = 64;
445
446#[derive(Clone, Debug, PartialEq, Eq)]
448#[non_exhaustive]
449pub enum RoleVersionsError {
450 TooMany { count: usize },
452 InvalidRole { role: String },
456 InvalidVersion { role: String, version: String },
459}
460
461impl RoleVersionsError {
462 pub fn field(&self) -> &'static str {
464 ROLE_VERSIONS_FIELD
465 }
466}
467
468impl std::fmt::Display for RoleVersionsError {
469 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
470 match self {
471 Self::TooMany { count } => write!(
472 f,
473 "{ROLE_VERSIONS_FIELD} has {count} entries; at most {MAX_ROLE_VERSIONS} are allowed"
474 ),
475 Self::InvalidRole { role } => write!(
476 f,
477 "{ROLE_VERSIONS_FIELD} names role {role:?}, which is not lowercase letters and \
478 digits in words joined by '-', at most {MAX_ROLE_NAME_LEN} bytes"
479 ),
480 Self::InvalidVersion { role, version } => write!(
481 f,
482 "{ROLE_VERSIONS_FIELD} gives role {role:?} version {version:?}, which is not 'v' \
483 followed by a positive integer without leading zeros"
484 ),
485 }
486 }
487}
488
489impl std::error::Error for RoleVersionsError {}
490
491pub fn validate_role_versions(
499 role_versions: &BTreeMap<String, String>,
500) -> Result<(), RoleVersionsError> {
501 if role_versions.len() > MAX_ROLE_VERSIONS {
502 return Err(RoleVersionsError::TooMany {
503 count: role_versions.len(),
504 });
505 }
506 for (role, version) in role_versions {
507 if !is_role_name(role) {
508 return Err(RoleVersionsError::InvalidRole { role: role.clone() });
509 }
510 if !is_role_version(version) {
511 return Err(RoleVersionsError::InvalidVersion {
512 role: role.clone(),
513 version: version.clone(),
514 });
515 }
516 }
517 Ok(())
518}
519
520fn is_role_name(role: &str) -> bool {
521 !role.is_empty()
522 && role.len() <= MAX_ROLE_NAME_LEN
523 && role.split('-').all(|word| {
524 !word.is_empty()
525 && word
526 .bytes()
527 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
528 })
529}
530
531fn is_role_version(version: &str) -> bool {
532 let bytes = version.as_bytes();
533 bytes.len() >= 2
534 && bytes[0] == b'v'
535 && (b'1'..=b'9').contains(&bytes[1])
536 && bytes[2..].iter().all(u8::is_ascii_digit)
537}
538
539#[cfg(test)]
540mod tests {
541 use super::*;
542
543 fn map(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
544 entries
545 .iter()
546 .map(|(role, version)| (role.to_string(), version.to_string()))
547 .collect()
548 }
549
550 #[test]
551 fn role_versions_accept_role_names_and_positive_versions() {
552 for entries in [
553 vec![],
554 vec![("tool-provider", "v1")],
555 vec![("a", "v9"), ("b2", "v10"), ("x-1-y", "v1203")],
556 ] {
557 assert_eq!(
558 validate_role_versions(&map(&entries)),
559 Ok(()),
560 "{entries:?}"
561 );
562 }
563 let longest = "a".repeat(MAX_ROLE_NAME_LEN);
564 assert_eq!(validate_role_versions(&map(&[(&longest, "v1")])), Ok(()));
565 let full: BTreeMap<String, String> = (0..MAX_ROLE_VERSIONS)
566 .map(|index| (format!("role-{index}"), "v1".to_string()))
567 .collect();
568 assert_eq!(validate_role_versions(&full), Ok(()));
569 }
570
571 #[test]
572 fn role_versions_refuse_malformed_role_names() {
573 let too_long = "a".repeat(MAX_ROLE_NAME_LEN + 1);
574 for role in [
575 "",
576 "Tool-provider",
577 "tool_provider",
578 "tool provider",
579 "-tool",
580 "tool-",
581 "tool--provider",
582 "tool.provider",
583 "outil-é",
584 too_long.as_str(),
585 ] {
586 let error = validate_role_versions(&map(&[(role, "v1")])).unwrap_err();
587 assert_eq!(
588 error,
589 RoleVersionsError::InvalidRole {
590 role: role.to_string()
591 },
592 "{role:?}"
593 );
594 assert_eq!(error.field(), "role_versions");
595 }
596 }
597
598 #[test]
599 fn role_versions_refuse_malformed_versions() {
600 for version in [
601 "", "v", "v0", "v01", "1", "V1", "v1.0", "v-1", "v1 ", " v1", "vx",
602 ] {
603 let error = validate_role_versions(&map(&[("tool-provider", version)])).unwrap_err();
604 assert_eq!(
605 error,
606 RoleVersionsError::InvalidVersion {
607 role: "tool-provider".to_string(),
608 version: version.to_string(),
609 },
610 "{version:?}"
611 );
612 assert_eq!(error.field(), "role_versions");
613 }
614 }
615
616 #[test]
617 fn role_versions_refuse_more_than_eight_entries() {
618 let nine: BTreeMap<String, String> = (0..=MAX_ROLE_VERSIONS)
619 .map(|index| (format!("role-{index}"), "v1".to_string()))
620 .collect();
621 let error = validate_role_versions(&nine).unwrap_err();
622 assert_eq!(error, RoleVersionsError::TooMany { count: 9 });
623 assert_eq!(error.field(), "role_versions");
624 assert!(error.to_string().starts_with("role_versions"), "{error}");
625 }
626
627 #[test]
628 fn route_bind_omits_absent_role_versions_and_carries_present_ones_verbatim() {
629 let bind = |role_versions| ModuleControlRequest::RouteBind {
630 route_channel: 1,
631 epoch: 1,
632 target: crate::RouteTarget::ToolProvider {
633 module_id: "aft".to_string(),
634 },
635 identity: crate::BindIdentity::new("/tmp/p", "h", "s"),
636 principal: None,
637 consumer_capabilities: None,
638 role_versions,
639 admission_facts: None,
640 scope: None,
641 call_mode: None,
642 };
643 let absent = serde_json::to_value(bind(None)).unwrap();
644 assert!(absent.get("role_versions").is_none(), "{absent}");
645 let present = bind(Some(map(&[("tool-provider", "v1")])));
646 let encoded = serde_json::to_value(&present).unwrap();
647 assert_eq!(
648 encoded["role_versions"],
649 serde_json::json!({ "tool-provider": "v1" })
650 );
651 let decoded: ModuleControlRequest = serde_json::from_value(encoded).unwrap();
652 assert_eq!(decoded, present);
653 }
654}