Skip to main content

alien_core/
sync.rs

1//! Sync protocol types for agent ↔ manager communication.
2//!
3//! The agent periodically calls `POST /v1/sync` with a `SyncRequest` and
4//! receives a `SyncResponse` containing the target deployment state.
5
6use 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/// State of an Operator capability as observed inside the environment.
16#[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    /// The Operator has the permission or local facility needed for the capability.
21    Granted,
22    /// The environment explicitly denied the capability.
23    Denied,
24    /// The capability does not apply in this environment.
25    Unavailable,
26}
27
28/// Report-only Operator capability status.
29#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
30#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
31#[serde(rename_all = "camelCase")]
32pub struct OperatorCapabilityReport {
33    /// Stable capability key, such as `k8s-workloads` or `logs`.
34    pub key: String,
35    /// Whether the capability is currently usable.
36    pub state: OperatorCapabilityState,
37    /// Optional human-readable detail from the Operator.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub detail: Option<String>,
40}
41
42/// A single operation the Operator currently has loaded. Opaque identifiers
43/// only — no tier, description, or other plugin business logic crosses into
44/// this public crate.
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
47#[serde(rename_all = "camelCase")]
48pub struct ReportedOperation {
49    /// Name of the plugin that owns this operation.
50    pub plugin: String,
51    /// Version of the plugin that owns this operation.
52    pub plugin_version: String,
53    /// Name of the operation within the plugin.
54    pub name: String,
55}
56
57/// Report-only summary of the operations the Operator has loaded, used to
58/// confirm a bundle sync actually took effect.
59#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
60#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
61#[serde(rename_all = "camelCase")]
62pub struct OperationsReport {
63    /// Hash of the enabled-plugin bundle set the Operator currently has
64    /// loaded. Compared against the platform's target hash to detect drift.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub loaded_bundle_hash: Option<String>,
67    /// Operations currently loaded and executable by the Operator.
68    #[serde(default, skip_serializing_if = "Vec::is_empty")]
69    pub operations: Vec<ReportedOperation>,
70}
71
72/// Origin of the exact Operator image running this process.
73#[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    /// The image came from an immutable generated package.
78    Package,
79    /// The image was configured directly by the installer.
80    Configured,
81}
82
83/// Exact immutable Operator image identity observed by the running process.
84#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
85#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
86#[serde(rename_all = "camelCase")]
87pub struct OperatorImageReport {
88    /// How the installer selected this image.
89    pub source: OperatorImageSource,
90    /// Package ID when `source` is `package`; otherwise `null`.
91    pub package_id: Option<String>,
92    /// Package version when `source` is `package`; otherwise `null`.
93    pub package_version: Option<String>,
94    /// Exact OCI image reference in `repository@sha256:digest` form.
95    pub image: String,
96    /// Exact lowercase OCI digest in `sha256:digest` form.
97    pub digest: String,
98}
99
100impl OperatorImageReport {
101    /// Validate that this report identifies one immutable image and that its
102    /// package fields agree with `source`.
103    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/// One bundle the Operator needs to download to reach `targetBundleHash`.
151/// The manager mints a short-lived presigned GET URL per bundle — the
152/// Operator never holds real cloud storage credentials, mirroring the OCI
153/// registry proxy's credential-injection pattern.
154#[derive(Clone, Serialize, Deserialize, PartialEq)]
155#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
156#[serde(rename_all = "camelCase")]
157pub struct OperationsBundleDownload {
158    /// Plugin name this bundle provides.
159    pub plugin: String,
160    /// Plugin version this bundle provides.
161    pub plugin_version: String,
162    /// Presigned URL to GET the bundle ZIP from. Short-lived.
163    pub url: String,
164    /// Environment the plugin process runs with: its settings, which may hold
165    /// secrets. Store only in encrypted state, and never log the values.
166    #[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/// Target operations-bundle set for the Operator to converge its loaded
181/// plugin registry toward, independent of any release/config target — a
182/// plugin can be enabled with no release change, so this is not nested under
183/// `TargetDeployment`.
184#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
185#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
186#[serde(rename_all = "camelCase")]
187pub struct TargetOperationsBundleSet {
188    /// Hash identifying this exact enabled-plugin set. Compare against
189    /// `OperationsReport.loadedBundleHash` to detect drift.
190    pub hash: String,
191    /// Presigned downloads for every bundle in the target set. The Operator
192    /// fetches only the ones it doesn't already have loaded at the right
193    /// version; already-loaded bundles are harmless to re-download.
194    #[serde(default, skip_serializing_if = "Vec::is_empty")]
195    pub bundles: Vec<OperationsBundleDownload>,
196}
197
198/// One release-independent container the Operator should run in its namespace.
199/// The manager sends the complete set on every sync. An empty set removes
200/// containers previously owned by this deployment.
201#[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    /// The container's variables its manager holds, as `cenv.<name>.<NAME>` slots with the
218    /// digests the sender planned with. When present, the manager adds exactly these values,
219    /// each checked against its kind and digest, and ignores anything else stored for the
220    /// container. When absent, the manager adds every value stored under the container's
221    /// prefix, as for senders that predate slot references. The manager removes the field
222    /// before the target reaches the Operator, so its API never carries it.
223    #[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    /// Stop an installed workload when its release no longer admits the image.
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub suspended_reason: Option<String>,
231}
232
233// Never include secret values in sync diagnostics.
234impl 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/// What the Operator observed after applying one target generation.
254#[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/// Request sent by the agent to the manager during periodic sync.
276#[derive(Debug, Clone, Serialize, Deserialize)]
277#[serde(rename_all = "camelCase")]
278pub struct SyncRequest {
279    /// The deployment ID this agent is managing.
280    pub deployment_id: String,
281    /// Stable identity for this Operator process. Used to fence update work.
282    #[serde(default)]
283    pub session: String,
284    /// Signals that this Operator persists and echoes execution claims.
285    #[serde(default)]
286    pub supports_execution_claims: bool,
287    /// Signals that this Operator understands container tunnels. Older
288    /// Operators reject stacks that declare one, so the manager leaves
289    /// tunnels out of their targets.
290    #[serde(default)]
291    pub supports_tunnels: bool,
292    /// Exact update claim returned by the previous sync response.
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub execution_claim: Option<SyncExecutionClaim>,
295    /// Current deployment state as seen by the agent.
296    #[serde(skip_serializing_if = "Option::is_none")]
297    pub current_state: Option<DeploymentState>,
298    /// Managed Alien resource status samples emitted by the Operator's deployment step.
299    #[serde(
300        default,
301        rename = "resourceHeartbeats",
302        skip_serializing_if = "Vec::is_empty"
303    )]
304    pub heartbeats: Vec<ResourceHeartbeat>,
305    /// Observed raw-resource inventory batches successfully read by the Operator.
306    #[serde(
307        default,
308        rename = "observedInventoryBatches",
309        skip_serializing_if = "Vec::is_empty"
310    )]
311    pub observed_inventory_batches: Vec<ObservedInventoryBatch>,
312    /// Report-only capabilities observed by the Operator.
313    #[serde(default, skip_serializing_if = "Vec::is_empty")]
314    pub capabilities: Vec<OperatorCapabilityReport>,
315    /// Version of the Operator binary reporting this sync.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub operator_version: Option<String>,
318    /// Report-only summary of the operations the Operator currently has
319    /// loaded. Absent means the Operator does not yet support reporting
320    /// this (older Operator versions), not that it has no operations.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub operations_report: Option<OperationsReport>,
323    /// Operations an Operator installed on its own declares through its
324    /// environment, without setting values. Absent when its deployment's
325    /// release declares them instead.
326    #[serde(default, skip_serializing_if = "Option::is_none")]
327    pub operations_config: Option<crate::OperationsConfig>,
328    /// The setup the installed chart carries. An observation, never a grant:
329    /// the manager decides whether it completes a pending setup update.
330    /// Absent when the Operator was not installed from a chart that records it.
331    #[serde(default, skip_serializing_if = "Option::is_none")]
332    pub installed_setup: Option<InstalledSetup>,
333}
334
335/// The setup an installed chart was built for, read from the Operator's own
336/// environment. It changes only when the chart's setup changes.
337#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
338#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
339#[serde(rename_all = "camelCase")]
340pub struct InstalledSetup {
341    /// Release the chart was built from.
342    pub release_id: String,
343    /// Setup target the chart was generated for.
344    pub setup_target: String,
345    /// Setup compatibility fingerprint embedded in the chart.
346    pub setup_fingerprint: String,
347    /// Fingerprint algorithm version.
348    pub setup_fingerprint_version: u32,
349    /// Helm release name the chart is installed as.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub release_name: Option<String>,
352    /// Kubernetes namespace of the Helm release.
353    #[serde(default, skip_serializing_if = "Option::is_none")]
354    pub namespace: Option<String>,
355}
356
357/// Where the Operator read the application identity from.
358#[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    /// Labels and pod statuses of the observed Kubernetes workloads.
363    Kubernetes,
364}
365
366/// A container image running in one observed application workload.
367#[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    /// Inventory identity of the workload, matching the `rawIdentity` of its
372    /// observed resource sample (for example `apps/v1:Deployment:shop:api`).
373    pub workload: String,
374    /// Container name within the workload.
375    pub container: String,
376    /// Image reference reported by the container runtime.
377    pub image: String,
378    /// Registry manifest digest in `sha256:<hex>` form, when the runtime
379    /// reports one.
380    #[serde(default, skip_serializing_if = "Option::is_none")]
381    pub digest: Option<String>,
382}
383
384/// Application release the Operator observes running in its environment.
385///
386/// This identifies the customer's application, not the Operator: the
387/// Operator's own image is reported separately as [`OperatorImageReport`].
388#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
389#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
390#[serde(rename_all = "camelCase")]
391pub struct ObservedApplicationReport {
392    /// Where this identity was read from.
393    pub source: ObservedApplicationSource,
394    /// Helm chart name from the workloads' `helm.sh/chart` label. Present only
395    /// when every labelled workload names the same chart.
396    #[serde(default, skip_serializing_if = "Option::is_none")]
397    pub chart_name: Option<String>,
398    /// Helm chart version from the same label.
399    #[serde(default, skip_serializing_if = "Option::is_none")]
400    pub chart_version: Option<String>,
401    /// Distinct container images running in the observed workloads.
402    #[serde(default, skip_serializing_if = "Vec::is_empty")]
403    pub images: Vec<ObservedApplicationImage>,
404    /// Whether every workload kind could be listed. When `false`, the chart
405    /// and images describe only the workloads the Operator could read.
406    pub complete: bool,
407    /// When the workloads were read.
408    pub observed_at: DateTime<Utc>,
409}
410
411/// Extensible wire input for sync metadata that is not part of the
412/// long-standing [`SyncRequest`] struct-literal contract.
413#[derive(Debug, Clone, Serialize)]
414#[serde(rename_all = "camelCase")]
415pub struct SyncInput {
416    /// Reader ceiling of this runtime, independent of the deployment writer version.
417    max_supported_deployment_protocol_version: u32,
418    #[serde(flatten)]
419    request: SyncRequest,
420    /// Exact immutable image identity injected by the installer. Absent for
421    /// older installations that do not carry an image receipt.
422    #[serde(skip_serializing_if = "Option::is_none")]
423    operator_image: Option<OperatorImageReport>,
424    /// Application release observed in the environment. Absent when the
425    /// Operator observed none or predates this report.
426    #[serde(skip_serializing_if = "Option::is_none")]
427    application: Option<ObservedApplicationReport>,
428    /// Absent for older Operators. An empty report means no containers remain.
429    #[serde(skip_serializing_if = "Option::is_none")]
430    dynamic_containers: Option<Vec<DynamicContainerReport>>,
431    /// Set when the Operator runs a settled release but holds no config for
432    /// it, for example after it moved from a token to an enrollment code.
433    /// The manager then sends the current release again so the Operator can
434    /// rebuild its config. Older managers ignore it.
435    #[serde(skip_serializing_if = "std::ops::Not::not")]
436    installed_config_missing: bool,
437    /// Set while the pull Secret the Operator's Deployment references holds
438    /// the Operator's own registry pull credential, or no such Secret needs
439    /// one. The manager keeps the Operator's old deployment token until it
440    /// sees this, because that token may still be the Secret's content.
441    /// Older managers ignore it.
442    #[serde(skip_serializing_if = "std::ops::Not::not")]
443    pull_secret_refreshed: bool,
444}
445
446impl SyncInput {
447    /// Start building a sync payload while preserving the stable
448    /// [`SyncRequest`] literal surface for downstream callers.
449    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
461/// Builder for optional sync receipts. New optional wire metadata belongs
462/// here so adding it does not break downstream [`SyncRequest`] literals.
463pub 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    /// Attach the immutable image receipt for the running Operator.
474    pub fn operator_image(mut self, operator_image: OperatorImageReport) -> Self {
475        self.operator_image = Some(operator_image);
476        self
477    }
478
479    /// Attach the application release observed in the environment.
480    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    /// Ask the manager for the installed release because its config is gone.
491    pub fn installed_config_missing(mut self, missing: bool) -> Self {
492        self.installed_config_missing = missing;
493        self
494    }
495
496    /// Tell the manager the Operator's pull Secret holds its own credential.
497    pub fn pull_secret_refreshed(mut self, refreshed: bool) -> Self {
498        self.pull_secret_refreshed = refreshed;
499        self
500    }
501
502    /// Finish the serializable sync payload.
503    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/// Response from the manager to the agent sync request.
518#[derive(Debug, Clone, Serialize, Deserialize)]
519#[serde(rename_all = "camelCase")]
520pub struct SyncResponse {
521    /// Exact operation attempt associated with `target`.
522    #[serde(default, skip_serializing_if = "Option::is_none")]
523    pub execution_claim: Option<SyncExecutionClaim>,
524    /// Authoritative deployment state from the manager.
525    ///
526    /// Pull agents use this to hydrate local state when attaching to an
527    /// already-imported deployment. Absent means the agent's local state is
528    /// already authoritative or no state has been established yet.
529    #[serde(default, skip_serializing_if = "Option::is_none")]
530    pub current_state: Option<DeploymentState>,
531    /// Target deployment the agent should converge toward.
532    /// None means no changes needed or this is an observe-only deployment.
533    #[serde(skip_serializing_if = "Option::is_none")]
534    pub target: Option<TargetDeployment>,
535    /// Public URL for the commands API (e.g. `https://manager.example.com/v1`).
536    /// Operators and app-owned receivers use this to lease pending commands;
537    /// Workers themselves receive pushes.
538    /// When absent, the agent falls back to its sync URL.
539    #[serde(default, skip_serializing_if = "Option::is_none")]
540    pub commands_url: Option<String>,
541    /// Target operations-bundle set the Operator should converge its loaded
542    /// plugin registry toward. None means no enabled plugin set has ever
543    /// been established for this project (nothing to sync), not that the
544    /// Operator is up to date — compare `hash` against the Operator's own
545    /// loaded hash to decide whether to download anything.
546    #[serde(default, skip_serializing_if = "Option::is_none")]
547    pub target_operations_bundle_set: Option<TargetOperationsBundleSet>,
548    /// Complete release-independent target set. None means the manager does
549    /// not support this protocol; Some(empty) means remove owned containers.
550    #[serde(default, skip_serializing_if = "Option::is_none")]
551    pub target_dynamic_containers: Option<Vec<TargetDynamicContainer>>,
552    /// Base URL the Operator opens tunnel connections to. None means the
553    /// manager does not accept tunnels, so the Operator never dials.
554    #[serde(default, skip_serializing_if = "Option::is_none")]
555    pub tunnel_url: Option<String>,
556    /// Operator image the manager wants this Operator to run. Operators that
557    /// manage their own workload update to it; None means no opinion.
558    #[serde(default, skip_serializing_if = "Option::is_none")]
559    pub target_operator_image: Option<String>,
560}
561
562#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
563#[serde(rename_all = "camelCase")]
564pub struct SyncExecutionClaim {
565    pub operation_id: String,
566    pub attempt_id: String,
567}
568
569/// Target deployment state for the agent to converge toward.
570#[derive(Debug, Clone, Serialize, Deserialize)]
571#[serde(rename_all = "camelCase")]
572pub struct TargetDeployment {
573    /// Release information (ID, version, stack definition).
574    pub release_info: ReleaseInfo,
575    /// Full deployment configuration (settings, env vars, etc.).
576    pub config: DeploymentConfig,
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582
583    #[test]
584    fn test_sync_request_serialization() {
585        let req = SyncRequest {
586            deployment_id: "dep_abc123".to_string(),
587            session: "operator-test".to_string(),
588            supports_execution_claims: true,
589            supports_tunnels: true,
590            execution_claim: None,
591            current_state: None,
592            heartbeats: Vec::new(),
593            observed_inventory_batches: Vec::new(),
594            capabilities: Vec::new(),
595            operator_version: None,
596            operations_report: None,
597            operations_config: None,
598            installed_setup: None,
599        };
600
601        let json = serde_json::to_value(&req).unwrap();
602        assert_eq!(json["deploymentId"], "dep_abc123");
603        assert_eq!(json["supportsExecutionClaims"], true);
604        // current_state is None → should be omitted
605        assert!(json.get("currentState").is_none());
606        assert!(json.get("resourceHeartbeats").is_none());
607        assert!(json.get("capabilities").is_none());
608        assert!(json.get("operatorVersion").is_none());
609        assert!(json.get("operatorImage").is_none());
610        assert!(json.get("operationsReport").is_none());
611    }
612
613    #[test]
614    fn test_sync_request_deserialization() {
615        let json = r#"{"deploymentId": "dep_xyz"}"#;
616        let req: SyncRequest = serde_json::from_str(json).unwrap();
617        assert_eq!(req.deployment_id, "dep_xyz");
618        assert!(req.session.is_empty());
619        assert!(!req.supports_execution_claims);
620        assert!(req.current_state.is_none());
621        assert!(req.heartbeats.is_empty());
622        assert!(req.observed_inventory_batches.is_empty());
623        assert!(req.capabilities.is_empty());
624        assert!(req.operator_version.is_none());
625        assert!(req.operations_report.is_none());
626    }
627
628    #[test]
629    fn test_sync_response_empty() {
630        let resp = SyncResponse {
631            execution_claim: None,
632            current_state: None,
633            target: None,
634            commands_url: None,
635            target_operations_bundle_set: None,
636            target_dynamic_containers: None,
637            tunnel_url: None,
638            target_operator_image: None,
639        };
640        let json = serde_json::to_value(&resp).unwrap();
641        // target is None → should be omitted
642        assert!(json.get("target").is_none());
643        assert!(json.get("currentState").is_none());
644        assert!(json.get("targetOperationsBundleSet").is_none());
645    }
646
647    #[test]
648    fn test_sync_response_roundtrip_no_target() {
649        let resp = SyncResponse {
650            execution_claim: None,
651            current_state: None,
652            target: None,
653            commands_url: None,
654            target_operations_bundle_set: None,
655            target_dynamic_containers: None,
656            tunnel_url: None,
657            target_operator_image: None,
658        };
659        let serialized = serde_json::to_string(&resp).unwrap();
660        let deserialized: SyncResponse = serde_json::from_str(&serialized).unwrap();
661        assert!(deserialized.target.is_none());
662        assert!(deserialized.current_state.is_none());
663    }
664
665    #[test]
666    fn test_sync_request_with_camel_case() {
667        // Verify camelCase renaming works correctly
668        let json = r#"{"deploymentId": "dep_1", "currentState": null}"#;
669        let req: SyncRequest = serde_json::from_str(json).unwrap();
670        assert_eq!(req.deployment_id, "dep_1");
671        assert!(req.current_state.is_none());
672        assert!(req.heartbeats.is_empty());
673        assert!(req.capabilities.is_empty());
674
675        // snake_case should NOT work
676        let json = r#"{"deployment_id": "dep_1"}"#;
677        assert!(serde_json::from_str::<SyncRequest>(json).is_err());
678    }
679
680    #[test]
681    fn test_sync_request_heartbeats_roundtrip() {
682        let json = serde_json::json!({
683            "deploymentId": "dep_1",
684            "resourceHeartbeats": [{
685                "deploymentId": "dep_1",
686                "resourceId": "api",
687                "resourceType": "container",
688                "controllerPlatform": "kubernetes",
689                "backend": "kubernetes",
690                "observedAt": "2026-01-01T00:00:00Z",
691                "data": {
692                    "resourceType": "container",
693                    "data": {
694                        "backend": "kubernetes",
695                        "status": {
696                            "health": "healthy",
697                            "lifecycle": "running",
698                            "message": null,
699                            "stale": false,
700                            "partial": false,
701                            "collectionIssues": []
702                        },
703                        "namespace": "default",
704                        "name": "api",
705                        "workloadKind": "deployment",
706                        "replicas": { "desired": 1, "current": 1, "ready": 1, "available": 1, "updated": null, "misscheduled": null },
707                        "restarts": 0,
708                        "cpu": null,
709                        "memory": null,
710                        "workload": null,
711                        "pods": [],
712                        "instances": [],
713                        "events": []
714                    }
715                },
716                "raw": []
717            }]
718        });
719
720        let req: SyncRequest = serde_json::from_value(json).unwrap();
721        assert_eq!(req.heartbeats.len(), 1);
722        assert_eq!(req.heartbeats[0].resource_id, "api");
723        assert!(req.capabilities.is_empty());
724
725        let serialized = serde_json::to_value(&req).unwrap();
726        assert_eq!(serialized["resourceHeartbeats"][0]["resourceId"], "api");
727    }
728
729    #[test]
730    fn test_sync_response_observe_only_state_roundtrip() {
731        let state = DeploymentState {
732            status: crate::DeploymentStatus::Running,
733            platform: crate::Platform::Kubernetes,
734            current_release: None,
735            target_release: None,
736            stack_state: None,
737            error: None,
738            environment_info: None,
739            runtime_metadata: None,
740            retry_requested: false,
741            protocol_version: crate::DEPLOYMENT_PROTOCOL_VERSION,
742        };
743        assert!(!state.has_desired());
744
745        let resp = SyncResponse {
746            execution_claim: None,
747            current_state: Some(state),
748            target: None,
749            commands_url: None,
750            target_operations_bundle_set: None,
751            target_dynamic_containers: None,
752            tunnel_url: None,
753            target_operator_image: None,
754        };
755
756        let serialized = serde_json::to_string(&resp).unwrap();
757        let deserialized: SyncResponse = serde_json::from_str(&serialized).unwrap();
758        let current_state = deserialized.current_state.unwrap();
759
760        assert_eq!(current_state.status, crate::DeploymentStatus::Running);
761        assert!(!current_state.has_desired());
762        assert!(deserialized.target.is_none());
763    }
764
765    #[test]
766    fn test_sync_request_operations_report_absent_by_default() {
767        // Simulates an old Operator that doesn't know about operationsReport:
768        // the field must default to None, never be required.
769        let json = r#"{"deploymentId": "dep_old_operator", "operatorVersion": "0.9.0"}"#;
770        let req: SyncRequest = serde_json::from_str(json).unwrap();
771        assert_eq!(req.operator_version.as_deref(), Some("0.9.0"));
772        assert!(req.operations_report.is_none());
773    }
774
775    #[test]
776    fn test_sync_request_operator_image_roundtrip() {
777        let digest = format!("sha256:{}", "a".repeat(64));
778        let report = OperatorImageReport {
779            source: OperatorImageSource::Package,
780            package_id: Some("pkg_operator".to_string()),
781            package_version: Some("1.2.3".to_string()),
782            image: format!("registry.example.com/operator@{digest}"),
783            digest,
784        };
785        report.validate().expect("valid package image report");
786
787        let value = serde_json::to_value(&report).unwrap();
788        assert_eq!(value["source"], "package");
789        assert_eq!(value["packageId"], "pkg_operator");
790        assert_eq!(value["packageVersion"], "1.2.3");
791
792        let decoded: OperatorImageReport = serde_json::from_value(value).unwrap();
793        assert_eq!(decoded, report);
794    }
795
796    #[test]
797    fn sync_input_adds_operator_image_without_expanding_sync_request() {
798        let digest = format!("sha256:{}", "a".repeat(64));
799        let request = SyncRequest {
800            deployment_id: "dep_1".to_string(),
801            session: String::new(),
802            supports_execution_claims: false,
803            supports_tunnels: false,
804            execution_claim: None,
805            current_state: None,
806            heartbeats: Vec::new(),
807            observed_inventory_batches: Vec::new(),
808            capabilities: Vec::new(),
809            operator_version: None,
810            operations_report: None,
811            operations_config: None,
812            installed_setup: None,
813        };
814        let input = SyncInput::builder(request)
815            .operator_image(OperatorImageReport {
816                source: OperatorImageSource::Configured,
817                package_id: None,
818                package_version: None,
819                image: format!("registry.example.com/operator@{digest}"),
820                digest,
821            })
822            .build();
823
824        let value = serde_json::to_value(input).unwrap();
825        assert_eq!(
826            value["maxSupportedDeploymentProtocolVersion"],
827            crate::MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION
828        );
829        let legacy_request: SyncRequest = serde_json::from_value(value.clone()).unwrap();
830        assert_eq!(legacy_request.deployment_id, "dep_1");
831        assert_eq!(value["deploymentId"], "dep_1");
832        assert_eq!(value["operatorImage"]["source"], "configured");
833    }
834
835    #[test]
836    fn sync_input_omits_absent_operator_image() {
837        let request = SyncRequest {
838            deployment_id: "dep_1".to_string(),
839            session: String::new(),
840            supports_execution_claims: false,
841            supports_tunnels: false,
842            execution_claim: None,
843            current_state: None,
844            heartbeats: Vec::new(),
845            observed_inventory_batches: Vec::new(),
846            capabilities: Vec::new(),
847            operator_version: None,
848            operations_report: None,
849            operations_config: None,
850            installed_setup: None,
851        };
852
853        let value = serde_json::to_value(SyncInput::builder(request).build()).unwrap();
854        assert!(value.get("operatorImage").is_none());
855    }
856
857    #[test]
858    fn operator_image_report_rejects_mutable_or_inconsistent_identity() {
859        let digest = format!("sha256:{}", "a".repeat(64));
860        let mutable = OperatorImageReport {
861            source: OperatorImageSource::Configured,
862            package_id: None,
863            package_version: None,
864            image: "registry.example.com/operator:latest".to_string(),
865            digest: digest.clone(),
866        };
867        assert_eq!(
868            mutable.validate(),
869            Err("operator image must use repository@sha256:digest form")
870        );
871
872        let mismatched = OperatorImageReport {
873            source: OperatorImageSource::Configured,
874            package_id: None,
875            package_version: None,
876            image: format!("registry.example.com/operator@sha256:{}", "b".repeat(64)),
877            digest,
878        };
879        assert_eq!(
880            mismatched.validate(),
881            Err("operator image must contain one repository and the reported digest")
882        );
883    }
884
885    #[test]
886    fn operator_image_report_enforces_source_specific_package_fields() {
887        let digest = format!("sha256:{}", "a".repeat(64));
888        let image = format!("registry.example.com/operator@{digest}");
889        let missing_package = OperatorImageReport {
890            source: OperatorImageSource::Package,
891            package_id: None,
892            package_version: None,
893            image: image.clone(),
894            digest: digest.clone(),
895        };
896        assert_eq!(
897            missing_package.validate(),
898            Err("package operator images require package ID and version")
899        );
900
901        let configured_with_package = OperatorImageReport {
902            source: OperatorImageSource::Configured,
903            package_id: Some("pkg_operator".to_string()),
904            package_version: Some("1.2.3".to_string()),
905            image,
906            digest,
907        };
908        assert_eq!(
909            configured_with_package.validate(),
910            Err("configured operator images must not include package identity")
911        );
912    }
913
914    #[test]
915    fn test_sync_request_operations_report_roundtrip() {
916        let req = SyncRequest {
917            deployment_id: "dep_1".to_string(),
918            session: String::new(),
919            supports_execution_claims: false,
920            supports_tunnels: false,
921            execution_claim: None,
922            current_state: None,
923            heartbeats: Vec::new(),
924            observed_inventory_batches: Vec::new(),
925            capabilities: Vec::new(),
926            operator_version: Some("1.2.3".to_string()),
927            operations_report: Some(OperationsReport {
928                loaded_bundle_hash: Some("builtin:s3@1.0.0:key|".to_string()),
929                operations: vec![ReportedOperation {
930                    plugin: "s3".to_string(),
931                    plugin_version: "1.0.0".to_string(),
932                    name: "list-buckets".to_string(),
933                }],
934            }),
935            operations_config: None,
936            installed_setup: None,
937        };
938
939        let json = serde_json::to_value(&req).unwrap();
940        assert_eq!(
941            json["operationsReport"]["loadedBundleHash"],
942            "builtin:s3@1.0.0:key|"
943        );
944        assert_eq!(json["operationsReport"]["operations"][0]["plugin"], "s3");
945        assert_eq!(
946            json["operationsReport"]["operations"][0]["pluginVersion"],
947            "1.0.0"
948        );
949        assert_eq!(
950            json["operationsReport"]["operations"][0]["name"],
951            "list-buckets"
952        );
953
954        let deserialized: SyncRequest = serde_json::from_value(json).unwrap();
955        assert_eq!(
956            deserialized
957                .operations_report
958                .as_ref()
959                .unwrap()
960                .loaded_bundle_hash,
961            req.operations_report.as_ref().unwrap().loaded_bundle_hash
962        );
963        assert_eq!(
964            deserialized.operations_report.unwrap().operations,
965            req.operations_report.unwrap().operations
966        );
967    }
968
969    #[test]
970    fn test_sync_response_target_operations_bundle_set_roundtrip() {
971        let resp = SyncResponse {
972            execution_claim: None,
973            current_state: None,
974            target: None,
975            commands_url: None,
976            target_operations_bundle_set: Some(TargetOperationsBundleSet {
977                hash: "builtin:s3@1.0.0:key|".to_string(),
978                bundles: vec![OperationsBundleDownload {
979                    plugin: "s3".to_string(),
980                    plugin_version: "1.0.0".to_string(),
981                    url: "https://storage.example.com/bundle.zip?sig=abc".to_string(),
982                    env: BTreeMap::new(),
983                }],
984            }),
985            target_dynamic_containers: None,
986            tunnel_url: None,
987            target_operator_image: None,
988        };
989
990        let json = serde_json::to_value(&resp).unwrap();
991        assert_eq!(
992            json["targetOperationsBundleSet"]["hash"],
993            "builtin:s3@1.0.0:key|"
994        );
995        assert_eq!(
996            json["targetOperationsBundleSet"]["bundles"][0]["plugin"],
997            "s3"
998        );
999
1000        let deserialized: SyncResponse = serde_json::from_value(json).unwrap();
1001        assert_eq!(
1002            deserialized.target_operations_bundle_set,
1003            resp.target_operations_bundle_set
1004        );
1005    }
1006
1007    #[test]
1008    fn test_sync_response_target_operations_bundle_set_absent_by_default() {
1009        let json = serde_json::json!({});
1010        let resp: SyncResponse = serde_json::from_value(json).unwrap();
1011        assert!(resp.target_operations_bundle_set.is_none());
1012    }
1013
1014    #[test]
1015    fn dynamic_container_sync_preserves_empty_target_and_hides_secrets_in_debug() {
1016        let old_manager_response: SyncResponse = serde_json::from_str("{}").unwrap();
1017        assert!(old_manager_response.target_dynamic_containers.is_none());
1018
1019        let empty_target = SyncResponse {
1020            execution_claim: None,
1021            current_state: None,
1022            target: None,
1023            commands_url: None,
1024            target_operations_bundle_set: None,
1025            target_dynamic_containers: Some(vec![]),
1026            tunnel_url: None,
1027            target_operator_image: None,
1028        };
1029        let json = serde_json::to_value(&empty_target).unwrap();
1030        assert_eq!(json["targetDynamicContainers"], serde_json::json!([]));
1031
1032        let target = TargetDynamicContainer {
1033            name: "api".to_string(),
1034            generation: 2,
1035            image: "example.com/api@sha256:abc".to_string(),
1036            cpu: "0.5".to_string(),
1037            memory: "512Mi".to_string(),
1038            replicas: 1,
1039            ports: vec![8080],
1040            deleted: false,
1041            env: BTreeMap::new(),
1042            secret_env: BTreeMap::from([("TOKEN".to_string(), "private-value".to_string())]),
1043            value_slots: None,
1044            health_check: None,
1045            suspended_reason: None,
1046        };
1047        assert!(!format!("{target:?}").contains("private-value"));
1048        let roundtrip: TargetDynamicContainer =
1049            serde_json::from_value(serde_json::to_value(&target).unwrap()).unwrap();
1050        assert_eq!(roundtrip, target);
1051    }
1052}