1use chrono::{DateTime, Utc};
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9
10use crate::{
11 DeploymentConfig, DeploymentState, ObservedInventoryBatch, ReleaseInfo, ResourceHeartbeat,
12 ValueSlotRef,
13};
14
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
17#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
18#[serde(rename_all = "kebab-case")]
19pub enum OperatorCapabilityState {
20 Granted,
22 Denied,
24 Unavailable,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
30#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
31#[serde(rename_all = "camelCase")]
32pub struct OperatorCapabilityReport {
33 pub key: String,
35 pub state: OperatorCapabilityState,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub detail: Option<String>,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
47#[serde(rename_all = "camelCase")]
48pub struct ReportedOperation {
49 pub plugin: String,
51 pub plugin_version: String,
53 pub name: String,
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
60#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
61#[serde(rename_all = "camelCase")]
62pub struct OperationsReport {
63 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub loaded_bundle_hash: Option<String>,
67 #[serde(default, skip_serializing_if = "Vec::is_empty")]
69 pub operations: Vec<ReportedOperation>,
70}
71
72#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
74#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
75#[serde(rename_all = "kebab-case")]
76pub enum OperatorImageSource {
77 Package,
79 Configured,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
85#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
86#[serde(rename_all = "camelCase")]
87pub struct OperatorImageReport {
88 pub source: OperatorImageSource,
90 pub package_id: Option<String>,
92 pub package_version: Option<String>,
94 pub image: String,
96 pub digest: String,
98}
99
100impl OperatorImageReport {
101 pub fn validate(&self) -> Result<(), &'static str> {
104 let Some(encoded_digest) = self.digest.strip_prefix("sha256:") else {
105 return Err("operator image digest must start with sha256:");
106 };
107 if encoded_digest.len() != 64
108 || !encoded_digest
109 .bytes()
110 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
111 {
112 return Err("operator image digest must contain 64 lowercase hex characters");
113 }
114
115 let Some((repository, image_digest)) = self.image.rsplit_once('@') else {
116 return Err("operator image must use repository@sha256:digest form");
117 };
118 if repository.is_empty()
119 || repository.chars().any(char::is_whitespace)
120 || repository.contains('@')
121 || image_digest != self.digest
122 {
123 return Err("operator image must contain one repository and the reported digest");
124 }
125
126 let package_id = self.package_id.as_deref().map(str::trim);
127 let package_version = self.package_version.as_deref().map(str::trim);
128 match self.source {
129 OperatorImageSource::Package
130 if package_id.is_some_and(|value| !value.is_empty())
131 && package_version.is_some_and(|value| !value.is_empty()) =>
132 {
133 Ok(())
134 }
135 OperatorImageSource::Package => {
136 Err("package operator images require package ID and version")
137 }
138 OperatorImageSource::Configured
139 if self.package_id.is_none() && self.package_version.is_none() =>
140 {
141 Ok(())
142 }
143 OperatorImageSource::Configured => {
144 Err("configured operator images must not include package identity")
145 }
146 }
147 }
148}
149
150#[derive(Clone, Serialize, Deserialize, PartialEq)]
155#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
156#[serde(rename_all = "camelCase")]
157pub struct OperationsBundleDownload {
158 pub plugin: String,
160 pub plugin_version: String,
162 pub url: String,
164 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
167 pub env: BTreeMap<String, String>,
168}
169
170impl std::fmt::Debug for OperationsBundleDownload {
171 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172 f.debug_struct("OperationsBundleDownload")
173 .field("plugin", &self.plugin)
174 .field("plugin_version", &self.plugin_version)
175 .field("env", &self.env.keys().collect::<Vec<_>>())
176 .finish_non_exhaustive()
177 }
178}
179
180#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
185#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
186#[serde(rename_all = "camelCase")]
187pub struct TargetOperationsBundleSet {
188 pub hash: String,
191 #[serde(default, skip_serializing_if = "Vec::is_empty")]
195 pub bundles: Vec<OperationsBundleDownload>,
196}
197
198#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
202#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
203#[serde(rename_all = "camelCase")]
204pub struct TargetDynamicContainer {
205 pub name: String,
206 pub generation: u64,
207 pub image: String,
208 pub cpu: String,
209 pub memory: String,
210 pub replicas: u32,
211 pub ports: Vec<u16>,
212 pub deleted: bool,
213 #[serde(default)]
214 pub env: BTreeMap<String, String>,
215 #[serde(default)]
216 pub secret_env: BTreeMap<String, String>,
217 #[serde(default, skip_serializing_if = "Option::is_none")]
224 #[cfg_attr(feature = "openapi", schema(ignore))]
225 pub value_slots: Option<Vec<ValueSlotRef>>,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub health_check: Option<DynamicContainerHealthCheck>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
230 pub suspended_reason: Option<String>,
231}
232
233impl std::fmt::Debug for TargetDynamicContainer {
235 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236 f.debug_struct("TargetDynamicContainer")
237 .field("name", &self.name)
238 .field("generation", &self.generation)
239 .field("image", &self.image)
240 .field("replicas", &self.replicas)
241 .finish_non_exhaustive()
242 }
243}
244
245#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
246#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
247#[serde(rename_all = "camelCase")]
248pub struct DynamicContainerHealthCheck {
249 pub path: String,
250 pub port: u16,
251}
252
253#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
255#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
256#[serde(rename_all = "camelCase")]
257pub struct DynamicContainerReport {
258 pub name: String,
259 pub generation: u64,
260 pub status: DynamicContainerStatus,
261 #[serde(default, skip_serializing_if = "Option::is_none")]
262 pub message: Option<String>,
263}
264
265#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
266#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
267#[serde(rename_all = "lowercase")]
268pub enum DynamicContainerStatus {
269 Pending,
270 Running,
271 Failing,
272 Stopped,
273}
274
275#[derive(Debug, Clone, Serialize, Deserialize)]
277#[serde(rename_all = "camelCase")]
278pub struct SyncRequest {
279 pub deployment_id: String,
281 #[serde(default)]
283 pub session: String,
284 #[serde(default)]
286 pub supports_execution_claims: bool,
287 #[serde(default)]
291 pub supports_pod_security: bool,
292 #[serde(default, skip_serializing_if = "Option::is_none")]
294 pub execution_claim: Option<SyncExecutionClaim>,
295 #[serde(skip_serializing_if = "Option::is_none")]
297 pub current_state: Option<DeploymentState>,
298 #[serde(
300 default,
301 rename = "resourceHeartbeats",
302 skip_serializing_if = "Vec::is_empty"
303 )]
304 pub heartbeats: Vec<ResourceHeartbeat>,
305 #[serde(
307 default,
308 rename = "observedInventoryBatches",
309 skip_serializing_if = "Vec::is_empty"
310 )]
311 pub observed_inventory_batches: Vec<ObservedInventoryBatch>,
312 #[serde(default, skip_serializing_if = "Vec::is_empty")]
314 pub capabilities: Vec<OperatorCapabilityReport>,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
317 pub operator_version: Option<String>,
318 #[serde(default, skip_serializing_if = "Option::is_none")]
322 pub operations_report: Option<OperationsReport>,
323 #[serde(default, skip_serializing_if = "Option::is_none")]
327 pub operations_config: Option<crate::OperationsConfig>,
328 #[serde(default, skip_serializing_if = "Option::is_none")]
332 pub installed_setup: Option<InstalledSetup>,
333}
334
335#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
338#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
339#[serde(rename_all = "camelCase")]
340pub struct InstalledSetup {
341 pub release_id: String,
343 pub setup_target: String,
345 pub setup_fingerprint: String,
347 pub setup_fingerprint_version: u32,
349 #[serde(default, skip_serializing_if = "Option::is_none")]
351 pub release_name: Option<String>,
352 #[serde(default, skip_serializing_if = "Option::is_none")]
354 pub namespace: Option<String>,
355}
356
357#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
359#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
360#[serde(rename_all = "camelCase")]
361pub enum ObservedApplicationSource {
362 Kubernetes,
364}
365
366#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
368#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
369#[serde(rename_all = "camelCase")]
370pub struct ObservedApplicationImage {
371 pub workload: String,
374 pub container: String,
376 pub image: String,
378 #[serde(default, skip_serializing_if = "Option::is_none")]
381 pub digest: Option<String>,
382}
383
384#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
389#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
390#[serde(rename_all = "camelCase")]
391pub struct ObservedApplicationReport {
392 pub source: ObservedApplicationSource,
394 #[serde(default, skip_serializing_if = "Option::is_none")]
397 pub chart_name: Option<String>,
398 #[serde(default, skip_serializing_if = "Option::is_none")]
400 pub chart_version: Option<String>,
401 #[serde(default, skip_serializing_if = "Vec::is_empty")]
403 pub images: Vec<ObservedApplicationImage>,
404 pub complete: bool,
407 pub observed_at: DateTime<Utc>,
409}
410
411#[derive(Debug, Clone, Serialize)]
414#[serde(rename_all = "camelCase")]
415pub struct SyncInput {
416 max_supported_deployment_protocol_version: u32,
418 #[serde(flatten)]
419 request: SyncRequest,
420 #[serde(skip_serializing_if = "Option::is_none")]
423 operator_image: Option<OperatorImageReport>,
424 #[serde(skip_serializing_if = "Option::is_none")]
427 application: Option<ObservedApplicationReport>,
428 #[serde(skip_serializing_if = "Option::is_none")]
430 dynamic_containers: Option<Vec<DynamicContainerReport>>,
431 #[serde(skip_serializing_if = "std::ops::Not::not")]
436 installed_config_missing: bool,
437 #[serde(skip_serializing_if = "std::ops::Not::not")]
443 pull_secret_refreshed: bool,
444}
445
446impl SyncInput {
447 pub fn builder(request: SyncRequest) -> SyncInputBuilder {
450 SyncInputBuilder {
451 request,
452 operator_image: None,
453 application: None,
454 dynamic_containers: None,
455 installed_config_missing: false,
456 pull_secret_refreshed: false,
457 }
458 }
459}
460
461pub struct SyncInputBuilder {
464 request: SyncRequest,
465 operator_image: Option<OperatorImageReport>,
466 application: Option<ObservedApplicationReport>,
467 dynamic_containers: Option<Vec<DynamicContainerReport>>,
468 installed_config_missing: bool,
469 pull_secret_refreshed: bool,
470}
471
472impl SyncInputBuilder {
473 pub fn operator_image(mut self, operator_image: OperatorImageReport) -> Self {
475 self.operator_image = Some(operator_image);
476 self
477 }
478
479 pub fn application(mut self, application: ObservedApplicationReport) -> Self {
481 self.application = Some(application);
482 self
483 }
484
485 pub fn dynamic_containers(mut self, reports: Vec<DynamicContainerReport>) -> Self {
486 self.dynamic_containers = Some(reports);
487 self
488 }
489
490 pub fn installed_config_missing(mut self, missing: bool) -> Self {
492 self.installed_config_missing = missing;
493 self
494 }
495
496 pub fn pull_secret_refreshed(mut self, refreshed: bool) -> Self {
498 self.pull_secret_refreshed = refreshed;
499 self
500 }
501
502 pub fn build(self) -> SyncInput {
504 SyncInput {
505 max_supported_deployment_protocol_version:
506 crate::MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION,
507 request: self.request,
508 operator_image: self.operator_image,
509 application: self.application,
510 dynamic_containers: self.dynamic_containers,
511 installed_config_missing: self.installed_config_missing,
512 pull_secret_refreshed: self.pull_secret_refreshed,
513 }
514 }
515}
516
517#[derive(Debug, Clone, Serialize, Deserialize)]
519#[serde(rename_all = "camelCase")]
520pub struct SyncResponse {
521 #[serde(default, skip_serializing_if = "Option::is_none")]
523 pub execution_claim: Option<SyncExecutionClaim>,
524 #[serde(default, skip_serializing_if = "Option::is_none")]
530 pub current_state: Option<DeploymentState>,
531 #[serde(skip_serializing_if = "Option::is_none")]
534 pub target: Option<TargetDeployment>,
535 #[serde(default, skip_serializing_if = "Option::is_none")]
540 pub commands_url: Option<String>,
541 #[serde(default, skip_serializing_if = "Option::is_none")]
547 pub target_operations_bundle_set: Option<TargetOperationsBundleSet>,
548 #[serde(default, skip_serializing_if = "Option::is_none")]
551 pub target_dynamic_containers: Option<Vec<TargetDynamicContainer>>,
552 #[serde(default, skip_serializing_if = "Option::is_none")]
555 pub target_operator_image: Option<String>,
556 #[serde(default, skip_serializing_if = "Option::is_none")]
560 pub signed_config: Option<crate::SignedStatement>,
561}
562
563#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
564#[serde(rename_all = "camelCase")]
565pub struct SyncExecutionClaim {
566 pub operation_id: String,
567 pub attempt_id: String,
568}
569
570#[derive(Debug, Clone, Serialize, Deserialize)]
572#[serde(rename_all = "camelCase")]
573pub struct TargetDeployment {
574 pub release_info: ReleaseInfo,
576 pub config: DeploymentConfig,
578 #[serde(default, skip_serializing_if = "Option::is_none")]
582 pub signed_config: Option<crate::SignedStatement>,
583}
584
585#[cfg(test)]
586mod tests {
587 use super::*;
588
589 #[test]
590 fn test_sync_request_serialization() {
591 let req = SyncRequest {
592 deployment_id: "dep_abc123".to_string(),
593 session: "operator-test".to_string(),
594 supports_execution_claims: true,
595 supports_pod_security: true,
596 execution_claim: None,
597 current_state: None,
598 heartbeats: Vec::new(),
599 observed_inventory_batches: Vec::new(),
600 capabilities: Vec::new(),
601 operator_version: None,
602 operations_report: None,
603 operations_config: None,
604 installed_setup: None,
605 };
606
607 let json = serde_json::to_value(&req).unwrap();
608 assert_eq!(json["deploymentId"], "dep_abc123");
609 assert_eq!(json["supportsExecutionClaims"], true);
610 assert!(json.get("currentState").is_none());
612 assert!(json.get("resourceHeartbeats").is_none());
613 assert!(json.get("capabilities").is_none());
614 assert!(json.get("operatorVersion").is_none());
615 assert!(json.get("operatorImage").is_none());
616 assert!(json.get("operationsReport").is_none());
617 }
618
619 #[test]
620 fn test_sync_request_deserialization() {
621 let json = r#"{"deploymentId": "dep_xyz"}"#;
622 let req: SyncRequest = serde_json::from_str(json).unwrap();
623 assert_eq!(req.deployment_id, "dep_xyz");
624 assert!(req.session.is_empty());
625 assert!(!req.supports_execution_claims);
626 assert!(req.current_state.is_none());
627 assert!(req.heartbeats.is_empty());
628 assert!(req.observed_inventory_batches.is_empty());
629 assert!(req.capabilities.is_empty());
630 assert!(req.operator_version.is_none());
631 assert!(req.operations_report.is_none());
632 }
633
634 #[test]
635 fn test_sync_response_empty() {
636 let resp = SyncResponse {
637 signed_config: None,
638 execution_claim: None,
639 current_state: None,
640 target: None,
641 commands_url: None,
642 target_operations_bundle_set: None,
643 target_dynamic_containers: None,
644 target_operator_image: None,
645 };
646 let json = serde_json::to_value(&resp).unwrap();
647 assert!(json.get("target").is_none());
649 assert!(json.get("currentState").is_none());
650 assert!(json.get("targetOperationsBundleSet").is_none());
651 }
652
653 #[test]
654 fn test_sync_response_roundtrip_no_target() {
655 let resp = SyncResponse {
656 signed_config: None,
657 execution_claim: None,
658 current_state: None,
659 target: None,
660 commands_url: None,
661 target_operations_bundle_set: None,
662 target_dynamic_containers: None,
663 target_operator_image: None,
664 };
665 let serialized = serde_json::to_string(&resp).unwrap();
666 let deserialized: SyncResponse = serde_json::from_str(&serialized).unwrap();
667 assert!(deserialized.target.is_none());
668 assert!(deserialized.current_state.is_none());
669 }
670
671 #[test]
672 fn test_sync_request_with_camel_case() {
673 let json = r#"{"deploymentId": "dep_1", "currentState": null}"#;
675 let req: SyncRequest = serde_json::from_str(json).unwrap();
676 assert_eq!(req.deployment_id, "dep_1");
677 assert!(req.current_state.is_none());
678 assert!(req.heartbeats.is_empty());
679 assert!(req.capabilities.is_empty());
680
681 let json = r#"{"deployment_id": "dep_1"}"#;
683 assert!(serde_json::from_str::<SyncRequest>(json).is_err());
684 }
685
686 #[test]
687 fn test_sync_request_heartbeats_roundtrip() {
688 let json = serde_json::json!({
689 "deploymentId": "dep_1",
690 "resourceHeartbeats": [{
691 "deploymentId": "dep_1",
692 "resourceId": "api",
693 "resourceType": "container",
694 "controllerPlatform": "kubernetes",
695 "backend": "kubernetes",
696 "observedAt": "2026-01-01T00:00:00Z",
697 "data": {
698 "resourceType": "container",
699 "data": {
700 "backend": "kubernetes",
701 "status": {
702 "health": "healthy",
703 "lifecycle": "running",
704 "message": null,
705 "stale": false,
706 "partial": false,
707 "collectionIssues": []
708 },
709 "namespace": "default",
710 "name": "api",
711 "workloadKind": "deployment",
712 "replicas": { "desired": 1, "current": 1, "ready": 1, "available": 1, "updated": null, "misscheduled": null },
713 "restarts": 0,
714 "cpu": null,
715 "memory": null,
716 "workload": null,
717 "pods": [],
718 "instances": [],
719 "events": []
720 }
721 },
722 "raw": []
723 }]
724 });
725
726 let req: SyncRequest = serde_json::from_value(json).unwrap();
727 assert_eq!(req.heartbeats.len(), 1);
728 assert_eq!(req.heartbeats[0].resource_id, "api");
729 assert!(req.capabilities.is_empty());
730
731 let serialized = serde_json::to_value(&req).unwrap();
732 assert_eq!(serialized["resourceHeartbeats"][0]["resourceId"], "api");
733 }
734
735 #[test]
736 fn test_sync_response_observe_only_state_roundtrip() {
737 let state = DeploymentState {
738 status: crate::DeploymentStatus::Running,
739 platform: crate::Platform::Kubernetes,
740 current_release: None,
741 target_release: None,
742 stack_state: None,
743 error: None,
744 environment_info: None,
745 runtime_metadata: None,
746 retry_requested: false,
747 protocol_version: crate::DEPLOYMENT_PROTOCOL_VERSION,
748 };
749 assert!(!state.has_desired());
750
751 let resp = SyncResponse {
752 signed_config: None,
753 execution_claim: None,
754 current_state: Some(state),
755 target: None,
756 commands_url: None,
757 target_operations_bundle_set: None,
758 target_dynamic_containers: None,
759 target_operator_image: None,
760 };
761
762 let serialized = serde_json::to_string(&resp).unwrap();
763 let deserialized: SyncResponse = serde_json::from_str(&serialized).unwrap();
764 let current_state = deserialized.current_state.unwrap();
765
766 assert_eq!(current_state.status, crate::DeploymentStatus::Running);
767 assert!(!current_state.has_desired());
768 assert!(deserialized.target.is_none());
769 }
770
771 #[test]
772 fn test_sync_request_operations_report_absent_by_default() {
773 let json = r#"{"deploymentId": "dep_old_operator", "operatorVersion": "0.9.0"}"#;
776 let req: SyncRequest = serde_json::from_str(json).unwrap();
777 assert_eq!(req.operator_version.as_deref(), Some("0.9.0"));
778 assert!(req.operations_report.is_none());
779 }
780
781 #[test]
782 fn test_sync_request_operator_image_roundtrip() {
783 let digest = format!("sha256:{}", "a".repeat(64));
784 let report = OperatorImageReport {
785 source: OperatorImageSource::Package,
786 package_id: Some("pkg_operator".to_string()),
787 package_version: Some("1.2.3".to_string()),
788 image: format!("registry.example.com/operator@{digest}"),
789 digest,
790 };
791 report.validate().expect("valid package image report");
792
793 let value = serde_json::to_value(&report).unwrap();
794 assert_eq!(value["source"], "package");
795 assert_eq!(value["packageId"], "pkg_operator");
796 assert_eq!(value["packageVersion"], "1.2.3");
797
798 let decoded: OperatorImageReport = serde_json::from_value(value).unwrap();
799 assert_eq!(decoded, report);
800 }
801
802 #[test]
803 fn sync_input_adds_operator_image_without_expanding_sync_request() {
804 let digest = format!("sha256:{}", "a".repeat(64));
805 let request = SyncRequest {
806 deployment_id: "dep_1".to_string(),
807 session: String::new(),
808 supports_execution_claims: false,
809 supports_pod_security: false,
810 execution_claim: None,
811 current_state: None,
812 heartbeats: Vec::new(),
813 observed_inventory_batches: Vec::new(),
814 capabilities: Vec::new(),
815 operator_version: None,
816 operations_report: None,
817 operations_config: None,
818 installed_setup: None,
819 };
820 let input = SyncInput::builder(request)
821 .operator_image(OperatorImageReport {
822 source: OperatorImageSource::Configured,
823 package_id: None,
824 package_version: None,
825 image: format!("registry.example.com/operator@{digest}"),
826 digest,
827 })
828 .build();
829
830 let value = serde_json::to_value(input).unwrap();
831 assert_eq!(
832 value["maxSupportedDeploymentProtocolVersion"],
833 crate::MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION
834 );
835 let legacy_request: SyncRequest = serde_json::from_value(value.clone()).unwrap();
836 assert_eq!(legacy_request.deployment_id, "dep_1");
837 assert_eq!(value["deploymentId"], "dep_1");
838 assert_eq!(value["operatorImage"]["source"], "configured");
839 }
840
841 #[test]
842 fn sync_input_omits_absent_operator_image() {
843 let request = SyncRequest {
844 deployment_id: "dep_1".to_string(),
845 session: String::new(),
846 supports_execution_claims: false,
847 supports_pod_security: false,
848 execution_claim: None,
849 current_state: None,
850 heartbeats: Vec::new(),
851 observed_inventory_batches: Vec::new(),
852 capabilities: Vec::new(),
853 operator_version: None,
854 operations_report: None,
855 operations_config: None,
856 installed_setup: None,
857 };
858
859 let value = serde_json::to_value(SyncInput::builder(request).build()).unwrap();
860 assert!(value.get("operatorImage").is_none());
861 }
862
863 #[test]
864 fn operator_image_report_rejects_mutable_or_inconsistent_identity() {
865 let digest = format!("sha256:{}", "a".repeat(64));
866 let mutable = OperatorImageReport {
867 source: OperatorImageSource::Configured,
868 package_id: None,
869 package_version: None,
870 image: "registry.example.com/operator:latest".to_string(),
871 digest: digest.clone(),
872 };
873 assert_eq!(
874 mutable.validate(),
875 Err("operator image must use repository@sha256:digest form")
876 );
877
878 let mismatched = OperatorImageReport {
879 source: OperatorImageSource::Configured,
880 package_id: None,
881 package_version: None,
882 image: format!("registry.example.com/operator@sha256:{}", "b".repeat(64)),
883 digest,
884 };
885 assert_eq!(
886 mismatched.validate(),
887 Err("operator image must contain one repository and the reported digest")
888 );
889 }
890
891 #[test]
892 fn operator_image_report_enforces_source_specific_package_fields() {
893 let digest = format!("sha256:{}", "a".repeat(64));
894 let image = format!("registry.example.com/operator@{digest}");
895 let missing_package = OperatorImageReport {
896 source: OperatorImageSource::Package,
897 package_id: None,
898 package_version: None,
899 image: image.clone(),
900 digest: digest.clone(),
901 };
902 assert_eq!(
903 missing_package.validate(),
904 Err("package operator images require package ID and version")
905 );
906
907 let configured_with_package = OperatorImageReport {
908 source: OperatorImageSource::Configured,
909 package_id: Some("pkg_operator".to_string()),
910 package_version: Some("1.2.3".to_string()),
911 image,
912 digest,
913 };
914 assert_eq!(
915 configured_with_package.validate(),
916 Err("configured operator images must not include package identity")
917 );
918 }
919
920 #[test]
921 fn test_sync_request_operations_report_roundtrip() {
922 let req = SyncRequest {
923 deployment_id: "dep_1".to_string(),
924 session: String::new(),
925 supports_execution_claims: false,
926 supports_pod_security: false,
927 execution_claim: None,
928 current_state: None,
929 heartbeats: Vec::new(),
930 observed_inventory_batches: Vec::new(),
931 capabilities: Vec::new(),
932 operator_version: Some("1.2.3".to_string()),
933 operations_report: Some(OperationsReport {
934 loaded_bundle_hash: Some("builtin:s3@1.0.0:key|".to_string()),
935 operations: vec![ReportedOperation {
936 plugin: "s3".to_string(),
937 plugin_version: "1.0.0".to_string(),
938 name: "list-buckets".to_string(),
939 }],
940 }),
941 operations_config: None,
942 installed_setup: None,
943 };
944
945 let json = serde_json::to_value(&req).unwrap();
946 assert_eq!(
947 json["operationsReport"]["loadedBundleHash"],
948 "builtin:s3@1.0.0:key|"
949 );
950 assert_eq!(json["operationsReport"]["operations"][0]["plugin"], "s3");
951 assert_eq!(
952 json["operationsReport"]["operations"][0]["pluginVersion"],
953 "1.0.0"
954 );
955 assert_eq!(
956 json["operationsReport"]["operations"][0]["name"],
957 "list-buckets"
958 );
959
960 let deserialized: SyncRequest = serde_json::from_value(json).unwrap();
961 assert_eq!(
962 deserialized
963 .operations_report
964 .as_ref()
965 .unwrap()
966 .loaded_bundle_hash,
967 req.operations_report.as_ref().unwrap().loaded_bundle_hash
968 );
969 assert_eq!(
970 deserialized.operations_report.unwrap().operations,
971 req.operations_report.unwrap().operations
972 );
973 }
974
975 #[test]
976 fn test_sync_response_target_operations_bundle_set_roundtrip() {
977 let resp = SyncResponse {
978 signed_config: None,
979 execution_claim: None,
980 current_state: None,
981 target: None,
982 commands_url: None,
983 target_operations_bundle_set: Some(TargetOperationsBundleSet {
984 hash: "builtin:s3@1.0.0:key|".to_string(),
985 bundles: vec![OperationsBundleDownload {
986 plugin: "s3".to_string(),
987 plugin_version: "1.0.0".to_string(),
988 url: "https://storage.example.com/bundle.zip?sig=abc".to_string(),
989 env: BTreeMap::new(),
990 }],
991 }),
992 target_dynamic_containers: None,
993 target_operator_image: None,
994 };
995
996 let json = serde_json::to_value(&resp).unwrap();
997 assert_eq!(
998 json["targetOperationsBundleSet"]["hash"],
999 "builtin:s3@1.0.0:key|"
1000 );
1001 assert_eq!(
1002 json["targetOperationsBundleSet"]["bundles"][0]["plugin"],
1003 "s3"
1004 );
1005
1006 let deserialized: SyncResponse = serde_json::from_value(json).unwrap();
1007 assert_eq!(
1008 deserialized.target_operations_bundle_set,
1009 resp.target_operations_bundle_set
1010 );
1011 }
1012
1013 #[test]
1014 fn test_sync_response_target_operations_bundle_set_absent_by_default() {
1015 let json = serde_json::json!({});
1016 let resp: SyncResponse = serde_json::from_value(json).unwrap();
1017 assert!(resp.target_operations_bundle_set.is_none());
1018 }
1019
1020 #[test]
1021 fn dynamic_container_sync_preserves_empty_target_and_hides_secrets_in_debug() {
1022 let old_manager_response: SyncResponse = serde_json::from_str("{}").unwrap();
1023 assert!(old_manager_response.target_dynamic_containers.is_none());
1024
1025 let empty_target = SyncResponse {
1026 signed_config: None,
1027 execution_claim: None,
1028 current_state: None,
1029 target: None,
1030 commands_url: None,
1031 target_operations_bundle_set: None,
1032 target_dynamic_containers: Some(vec![]),
1033 target_operator_image: None,
1034 };
1035 let json = serde_json::to_value(&empty_target).unwrap();
1036 assert_eq!(json["targetDynamicContainers"], serde_json::json!([]));
1037
1038 let target = TargetDynamicContainer {
1039 name: "api".to_string(),
1040 generation: 2,
1041 image: "example.com/api@sha256:abc".to_string(),
1042 cpu: "0.5".to_string(),
1043 memory: "512Mi".to_string(),
1044 replicas: 1,
1045 ports: vec![8080],
1046 deleted: false,
1047 env: BTreeMap::new(),
1048 secret_env: BTreeMap::from([("TOKEN".to_string(), "private-value".to_string())]),
1049 value_slots: None,
1050 health_check: None,
1051 suspended_reason: None,
1052 };
1053 assert!(!format!("{target:?}").contains("private-value"));
1054 let roundtrip: TargetDynamicContainer =
1055 serde_json::from_value(serde_json::to_value(&target).unwrap()).unwrap();
1056 assert_eq!(roundtrip, target);
1057 }
1058}