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}
293
294impl OperatorConfirmRequest {
295 pub fn new(summary: impl Into<String>, route_channel: u16, route_epoch: u32) -> Self {
296 Self {
297 op: OperatorConfirmOp::Confirm,
298 summary: summary.into(),
299 route_channel,
300 route_epoch,
301 }
302 }
303}
304
305#[non_exhaustive]
310#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
311pub struct OperatorConfirmReply {
312 op: OperatorConfirmOp,
313 pub outcome: String,
314}
315
316impl OperatorConfirmReply {
317 pub fn confirmed() -> Self {
318 Self {
319 op: OperatorConfirmOp::Confirm,
320 outcome: "confirmed".to_string(),
321 }
322 }
323}
324
325#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
328enum OperatorConfirmOp {
329 #[serde(rename = "operator.confirm")]
330 Confirm,
331}
332
333impl From<HealthReport> for ModuleControlResponse {
334 fn from(report: HealthReport) -> Self {
335 Self::HealthCheck {
336 status: report.status,
337 detail: report.detail,
338 metrics: report.metrics,
339 }
340 }
341}
342
343impl ModuleControlResponse {
344 pub fn health_report(&self) -> Option<HealthReport> {
345 match self {
346 Self::HealthCheck {
347 status,
348 detail,
349 metrics,
350 } => Some(HealthReport {
351 status: *status,
352 detail: detail.clone(),
353 metrics: metrics.clone(),
354 }),
355 Self::RouteBindAck {} => None,
356 }
357 }
358}
359
360#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
362#[serde(tag = "op")]
363pub enum ModuleControlPush {
364 #[serde(rename = "route.status")]
365 RouteStatus {
366 route_channel: u16,
367 route_epoch: u32,
368 status: String,
369 },
370}
371
372pub const ROLE_VERSIONS_FIELD: &str = "role_versions";
376
377pub const MAX_ROLE_VERSIONS: usize = 8;
379
380pub const MAX_ROLE_NAME_LEN: usize = 64;
382
383#[derive(Clone, Debug, PartialEq, Eq)]
385#[non_exhaustive]
386pub enum RoleVersionsError {
387 TooMany { count: usize },
389 InvalidRole { role: String },
393 InvalidVersion { role: String, version: String },
396}
397
398impl RoleVersionsError {
399 pub fn field(&self) -> &'static str {
401 ROLE_VERSIONS_FIELD
402 }
403}
404
405impl std::fmt::Display for RoleVersionsError {
406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407 match self {
408 Self::TooMany { count } => write!(
409 f,
410 "{ROLE_VERSIONS_FIELD} has {count} entries; at most {MAX_ROLE_VERSIONS} are allowed"
411 ),
412 Self::InvalidRole { role } => write!(
413 f,
414 "{ROLE_VERSIONS_FIELD} names role {role:?}, which is not lowercase letters and \
415 digits in words joined by '-', at most {MAX_ROLE_NAME_LEN} bytes"
416 ),
417 Self::InvalidVersion { role, version } => write!(
418 f,
419 "{ROLE_VERSIONS_FIELD} gives role {role:?} version {version:?}, which is not 'v' \
420 followed by a positive integer without leading zeros"
421 ),
422 }
423 }
424}
425
426impl std::error::Error for RoleVersionsError {}
427
428pub fn validate_role_versions(
436 role_versions: &BTreeMap<String, String>,
437) -> Result<(), RoleVersionsError> {
438 if role_versions.len() > MAX_ROLE_VERSIONS {
439 return Err(RoleVersionsError::TooMany {
440 count: role_versions.len(),
441 });
442 }
443 for (role, version) in role_versions {
444 if !is_role_name(role) {
445 return Err(RoleVersionsError::InvalidRole { role: role.clone() });
446 }
447 if !is_role_version(version) {
448 return Err(RoleVersionsError::InvalidVersion {
449 role: role.clone(),
450 version: version.clone(),
451 });
452 }
453 }
454 Ok(())
455}
456
457fn is_role_name(role: &str) -> bool {
458 !role.is_empty()
459 && role.len() <= MAX_ROLE_NAME_LEN
460 && role.split('-').all(|word| {
461 !word.is_empty()
462 && word
463 .bytes()
464 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
465 })
466}
467
468fn is_role_version(version: &str) -> bool {
469 let bytes = version.as_bytes();
470 bytes.len() >= 2
471 && bytes[0] == b'v'
472 && (b'1'..=b'9').contains(&bytes[1])
473 && bytes[2..].iter().all(u8::is_ascii_digit)
474}
475
476#[cfg(test)]
477mod tests {
478 use super::*;
479
480 fn map(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
481 entries
482 .iter()
483 .map(|(role, version)| (role.to_string(), version.to_string()))
484 .collect()
485 }
486
487 #[test]
488 fn role_versions_accept_role_names_and_positive_versions() {
489 for entries in [
490 vec![],
491 vec![("tool-provider", "v1")],
492 vec![("a", "v9"), ("b2", "v10"), ("x-1-y", "v1203")],
493 ] {
494 assert_eq!(
495 validate_role_versions(&map(&entries)),
496 Ok(()),
497 "{entries:?}"
498 );
499 }
500 let longest = "a".repeat(MAX_ROLE_NAME_LEN);
501 assert_eq!(validate_role_versions(&map(&[(&longest, "v1")])), Ok(()));
502 let full: BTreeMap<String, String> = (0..MAX_ROLE_VERSIONS)
503 .map(|index| (format!("role-{index}"), "v1".to_string()))
504 .collect();
505 assert_eq!(validate_role_versions(&full), Ok(()));
506 }
507
508 #[test]
509 fn role_versions_refuse_malformed_role_names() {
510 let too_long = "a".repeat(MAX_ROLE_NAME_LEN + 1);
511 for role in [
512 "",
513 "Tool-provider",
514 "tool_provider",
515 "tool provider",
516 "-tool",
517 "tool-",
518 "tool--provider",
519 "tool.provider",
520 "outil-é",
521 too_long.as_str(),
522 ] {
523 let error = validate_role_versions(&map(&[(role, "v1")])).unwrap_err();
524 assert_eq!(
525 error,
526 RoleVersionsError::InvalidRole {
527 role: role.to_string()
528 },
529 "{role:?}"
530 );
531 assert_eq!(error.field(), "role_versions");
532 }
533 }
534
535 #[test]
536 fn role_versions_refuse_malformed_versions() {
537 for version in [
538 "", "v", "v0", "v01", "1", "V1", "v1.0", "v-1", "v1 ", " v1", "vx",
539 ] {
540 let error = validate_role_versions(&map(&[("tool-provider", version)])).unwrap_err();
541 assert_eq!(
542 error,
543 RoleVersionsError::InvalidVersion {
544 role: "tool-provider".to_string(),
545 version: version.to_string(),
546 },
547 "{version:?}"
548 );
549 assert_eq!(error.field(), "role_versions");
550 }
551 }
552
553 #[test]
554 fn role_versions_refuse_more_than_eight_entries() {
555 let nine: BTreeMap<String, String> = (0..=MAX_ROLE_VERSIONS)
556 .map(|index| (format!("role-{index}"), "v1".to_string()))
557 .collect();
558 let error = validate_role_versions(&nine).unwrap_err();
559 assert_eq!(error, RoleVersionsError::TooMany { count: 9 });
560 assert_eq!(error.field(), "role_versions");
561 assert!(error.to_string().starts_with("role_versions"), "{error}");
562 }
563
564 #[test]
565 fn route_bind_omits_absent_role_versions_and_carries_present_ones_verbatim() {
566 let bind = |role_versions| ModuleControlRequest::RouteBind {
567 route_channel: 1,
568 epoch: 1,
569 target: crate::RouteTarget::ToolProvider {
570 module_id: "aft".to_string(),
571 },
572 identity: crate::BindIdentity::new("/tmp/p", "h", "s"),
573 principal: None,
574 consumer_capabilities: None,
575 role_versions,
576 admission_facts: None,
577 scope: None,
578 call_mode: None,
579 };
580 let absent = serde_json::to_value(bind(None)).unwrap();
581 assert!(absent.get("role_versions").is_none(), "{absent}");
582 let present = bind(Some(map(&[("tool-provider", "v1")])));
583 let encoded = serde_json::to_value(&present).unwrap();
584 assert_eq!(
585 encoded["role_versions"],
586 serde_json::json!({ "tool-provider": "v1" })
587 );
588 let decoded: ModuleControlRequest = serde_json::from_value(encoded).unwrap();
589 assert_eq!(decoded, present);
590 }
591}