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 reads the `security` profile settings
288    /// (`unrestricted`, `writablePaths`, optional ids). Absent for older
289    /// Operators, which reject a target that uses them.
290    #[serde(default)]
291    pub supports_pod_security: 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    /// Operator image the manager wants this Operator to run. Operators that
553    /// manage their own workload update to it; None means no opinion.
554    #[serde(default, skip_serializing_if = "Option::is_none")]
555    pub target_operator_image: Option<String>,
556    /// This deployment's newest signed `config/v1`, on every sync. A
557    /// protected Operator applies its installed release again when it is
558    /// newer than the config it last applied.
559    #[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/// Target deployment state for the agent to converge toward.
571#[derive(Debug, Clone, Serialize, Deserialize)]
572#[serde(rename_all = "camelCase")]
573pub struct TargetDeployment {
574    /// Release information (ID, version, stack definition).
575    pub release_info: ReleaseInfo,
576    /// Full deployment configuration (settings, env vars, etc.).
577    pub config: DeploymentConfig,
578    /// This deployment's newest signed `config/v1`: the developer's input
579    /// values and env, for a protected deployment that takes them only from
580    /// a signed statement.
581    #[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        // current_state is None → should be omitted
611        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        // target is None → should be omitted
648        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        // Verify camelCase renaming works correctly
674        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        // snake_case should NOT work
682        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        // Simulates an old Operator that doesn't know about operationsReport:
774        // the field must default to None, never be required.
775        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}