Skip to main content

alien_core/deployment/
state.rs

1//! Deployment state, step results, and runtime metadata.
2
3use crate::{ObservedInventoryBatch, Platform, ResourceHeartbeat, StackState};
4use alien_error::AlienError;
5use bon::Builder;
6use indexmap::IndexMap;
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9
10use super::{DeploymentStatus, EnvironmentInfo, ReleaseInfo};
11
12/// Actor that owns structural work during the initial setup phase.
13#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
14#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
15#[serde(rename_all = "camelCase")]
16pub enum InitialSetupAuthority {
17    /// Setup state was registered by an external setup engine. Alien may only
18    /// continue controller states that the importer explicitly initialized.
19    #[default]
20    ImportedHandoff,
21    /// Alien is the setup engine and is running with administrator credentials.
22    DirectSetup,
23}
24
25/// One-shot authority for a setup re-import to replace setup-owned resources.
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
27#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
28#[serde(rename_all = "camelCase")]
29pub struct SetupUpdateAuthorization {
30    /// Unique revision used by persistence layers for compare-and-swap updates.
31    pub nonce: String,
32    /// Setup resources and permissions digest (`Stack::setup_update_digest`) of the last
33    /// successful deployment. The field name is retained for serialized compatibility.
34    pub baseline_frozen_digest: String,
35    /// Setup resources and permissions digest (`Stack::setup_update_digest`) of the stack
36    /// the setup re-import prepared.
37    pub target_frozen_digest: String,
38    /// Release whose stack was prepared by setup.
39    pub release_id: String,
40    /// Stable setup target recorded on the imported deployment.
41    pub setup_target: String,
42    /// Exact setup artifact revision that authored this authority.
43    pub setup_fingerprint: String,
44    /// Setup fingerprint contract version.
45    pub setup_fingerprint_version: u32,
46}
47
48/// A setup report the manager declined, for display next to the waiting update.
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
51#[serde(rename_all = "camelCase")]
52pub struct SetupReportRefusal {
53    /// Plain-language reason, safe to show to the customer.
54    pub reason: String,
55    /// Release the chart reported.
56    pub reported_release_id: String,
57    /// When the manager declined it.
58    pub at: chrono::DateTime<chrono::Utc>,
59}
60
61/// A waiting release whose setup change a Helm chart upgrade cannot carry. The
62/// manager works this out from the release and the installed setup, so every
63/// place that offers an upgrade agrees with the manager's report handling.
64#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
65#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
66#[serde(rename_all = "camelCase")]
67pub struct CloudSetupRequired {
68    /// The waiting release this applies to.
69    pub release_id: String,
70    /// Plain-language reason, safe to show to the customer.
71    pub reason: String,
72}
73
74/// The Helm release an Operator reports it was installed as, so the exact
75/// upgrade command can be shown. Reported, never trusted for authority.
76#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
77#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
78#[serde(rename_all = "camelCase")]
79pub struct InstalledHelmRelease {
80    /// Release name, as passed to `helm install`.
81    pub name: String,
82    /// Kubernetes namespace the release is installed in.
83    pub namespace: String,
84}
85
86/// A credential outage's durable retry window, scoped to its deployment phase.
87#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
88#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
89#[serde(rename_all = "camelCase")]
90pub struct CredentialRetry {
91    /// First credential failure in this phase; subsequent attempts keep this timestamp.
92    pub started_at: chrono::DateTime<chrono::Utc>,
93    /// Changing phase starts a new window instead of carrying a previous outage forward.
94    pub status: DeploymentStatus,
95}
96
97/// Explicit disposition of durable data when deleting a deployment.
98/// Missing values from older checkpoints always preserve data.
99#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
100#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
101#[serde(rename_all = "camelCase")]
102pub enum DeletionPolicy {
103    #[default]
104    Retain,
105    Erase,
106}
107
108/// When an air-gapped site's latest status was written and received.
109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
110#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
111#[serde(rename_all = "camelCase")]
112pub struct AirgappedReportMetadata {
113    /// Site clock time; absent for reports from older clients.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub written_at: Option<chrono::DateTime<chrono::Utc>>,
116    /// Manager clock time when the report was accepted.
117    pub received_at: chrono::DateTime<chrono::Utc>,
118}
119
120/// Runtime metadata for deployment
121///
122/// Stores deployment state that needs to persist across step calls.
123#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
124#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
125#[serde(rename_all = "camelCase")]
126pub struct RuntimeMetadata {
127    /// User-authorized data disposition, persisted before deletion starts.
128    #[serde(default)]
129    pub deletion_policy: DeletionPolicy,
130
131    /// Most recent air-gapped report accepted by the manager.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub airgapped_report: Option<AirgappedReportMetadata>,
134
135    /// Version of the Operator binary that last reported this deployment, set
136    /// by the manager from the sync request. Missing until an Operator that
137    /// reports its version has synced.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub operator_version: Option<String>,
140
141    /// Bounded credential retry state shared by all deployment drivers.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub credential_retry: Option<CredentialRetry>,
144
145    /// Actor authorized to perform structural Frozen-resource work during
146    /// InitialSetup. Missing legacy values fail closed as ImportedHandoff.
147    #[serde(default)]
148    pub initial_setup_authority: InitialSetupAuthority,
149
150    /// Setup-owned grant to keep using the direct setup executor for updates.
151    /// Runtime settings and release contents must never create or change this grant.
152    #[serde(default, skip_serializing_if = "super::is_false")]
153    pub automatic_setup: bool,
154
155    /// Hash of the environment variables snapshot that was last synced to the vault
156    /// Used to avoid redundant sync operations during incremental deployment
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub last_synced_env_vars_hash: Option<String>,
159
160    /// Exact vault keys owned by the deployment secret synchronizer. This
161    /// inventory lets a later snapshot delete removed keys without listing or
162    /// touching unrelated values in the same vault.
163    #[serde(default, skip_serializing_if = "Vec::is_empty")]
164    pub last_synced_secret_names: Vec<String>,
165
166    /// Credential revocation completed before resource teardown. A delete retry
167    /// can use this receipt after the vault or its binding is gone. Secret sync
168    /// clears it before a deployment can write runtime credentials again.
169    #[serde(default, skip_serializing_if = "is_false")]
170    pub vault_credentials_revoked: bool,
171
172    /// Digest of the installed data inventory whose runtime public-access and
173    /// expiry configuration was protected before cleanup. The serialized field
174    /// name is retained for compatibility. This is not a
175    /// receipt for effective expiry propagation or privileged setup teardown.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub retained_storage_protection_hash: Option<String>,
178
179    /// UTC API-confirmation time for the matching data protection digest.
180    /// Provider propagation must be qualified separately before final retention.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub retained_storage_protection_confirmed_at: Option<chrono::DateTime<chrono::Utc>>,
183
184    /// Start of the bounded wait for retained data's expiry controls to disable.
185    /// Cleared on confirmation, explicit retry, or returning to normal execution.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub retained_data_protection_started_at: Option<chrono::DateTime<chrono::Utc>>,
188
189    /// The prepared (mutated) stack from the last successful deployment phase
190    /// This is the stack AFTER mutations have been applied (with service accounts, vault, etc.)
191    /// Used for compatibility checks during updates to compare mutated stacks
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub prepared_stack: Option<crate::Stack>,
194
195    /// Canonical resolved answers for inputs that gate Frozen resources,
196    /// keyed by input id, recorded when the deployment is created or its
197    /// setup import registers.
198    ///
199    /// Manual installations keep these answers fixed. An installation with an
200    /// ongoing-management grant refreshes them when preparing a release. Live
201    /// resources sharing a gate use the same recorded answer as Frozen resources.
202    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
203    pub persisted_gate_answers: GateAnswers,
204
205    /// Prepared target for an update that has not reached Running yet. Keeping
206    /// it separate preserves the last successful baseline across retries.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub pending_prepared_stack: Option<crate::Stack>,
209
210    /// Release the in-flight stack was prepared from: `pending_prepared_stack`
211    /// during updates, or `prepared_stack` during local first startup. The target can move
212    /// to a newer release while that stack is still being applied; this tells
213    /// the update which release actually converged.
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub pending_prepared_release_id: Option<String>,
216
217    /// One-shot setup update authority. It contains only non-secret identity
218    /// and canonical resource digests, never the imported payload or tokens.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub setup_update_authorization: Option<SetupUpdateAuthorization>,
221
222    /// Why the manager last declined a setup report from the installed chart,
223    /// with when. Cleared when a report is accepted or no longer needed.
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub setup_report_refusal: Option<SetupReportRefusal>,
226
227    /// Set while the waiting release changes something only the cloud setup
228    /// can apply, so a chart upgrade is not offered for it.
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub cloud_setup_required: Option<CloudSetupRequired>,
231
232    /// The Helm release the Operator reported it runs as.
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub installed_helm_release: Option<InstalledHelmRelease>,
235
236    /// Last generated CLI package revision whose direct setup was applied.
237    /// This lets a newer generated CLI refresh setup-owned infrastructure once
238    /// before handing runtime changes back to the hosted manager.
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub direct_setup_revision: Option<String>,
241
242    /// Whether cross-account registry access has been successfully granted.
243    /// Set to true after the manager successfully sets the ECR/GAR repo policy
244    /// for this deployment's target account. Prevents redundant API calls on
245    /// every reconcile tick.
246    #[serde(default, skip_serializing_if = "is_false")]
247    pub registry_access_granted: bool,
248
249    /// What that grant opened, compared against what the deployment needs now so a grant made
250    /// before a resource existed is finished rather than skipped, and the revoke names what was
251    /// granted. Absent on a grant recorded before this field existed.
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub registry_access: Option<RegistryAccess>,
254
255    /// What a direct setup created for resources it does not own, keyed by resource id. Setup
256    /// teardown removes exactly what is recorded here.
257    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
258    pub setup_scaffolding: BTreeMap<String, SetupScaffolding>,
259
260    /// Whether each vault-native deployer secret is in the customer's secret
261    /// store, with where it goes. Checked from metadata only; no value is ever
262    /// read or recorded here.
263    #[serde(default, skip_serializing_if = "Vec::is_empty")]
264    pub deployer_secrets: Vec<crate::DeployerSecretReport>,
265
266    /// What a one-token call with the customer admin's setup credentials said about each
267    /// model an AI resource declares. Written once, during setup; the AI controller's heartbeat
268    /// reports it. Absent when no model is declared or the setup could not check.
269    #[serde(default, skip_serializing_if = "Vec::is_empty")]
270    pub ai_access_checks: Vec<AiAccessCheck>,
271    /// When `deployer_secrets` was last read from the customer's secret store. While the
272    /// deployment waits for secrets the check is repeated at most every 30 seconds, because
273    /// the engine steps much faster than the store's rate limits allow.
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub deployer_secrets_checked_at: Option<chrono::DateTime<chrono::Utc>>,
276
277    /// Resources held back while a required deployer secret is missing: the ones that read
278    /// it and everything that depends on them. Everything else keeps installing. Empty once
279    /// no required secret is missing. An Operator that predates this field leaves it absent,
280    /// so readers must treat absence as unknown.
281    #[serde(default, skip_serializing_if = "Vec::is_empty")]
282    pub resources_waiting_for_secrets: Vec<String>,
283}
284
285/// The setup-time answer for one declared model.
286#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
287#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
288#[serde(rename_all = "camelCase")]
289pub struct AiAccessCheck {
290    /// The AI resource that declares the model.
291    pub resource_id: String,
292    /// The model id as the app uses it.
293    pub model_id: String,
294    /// `verified`, `refused` (the cloud refused the model) or `not-checked`.
295    pub result: AiAccessCheckResult,
296    /// The cloud's error code or the reason the check could not run.
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub detail: Option<String>,
299    pub tested_at: chrono::DateTime<chrono::Utc>,
300}
301
302#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
303#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
304#[serde(rename_all = "kebab-case")]
305pub enum AiAccessCheckResult {
306    Verified,
307    Refused,
308    NotChecked,
309}
310
311/// Cloud objects a direct setup created so a runtime-owned resource can run.
312#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
313#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
314#[serde(rename_all = "camelCase", tag = "type")]
315pub enum SetupScaffolding {
316    /// An AWS sandbox's image-build role, and for `egress: deny` its egress objects.
317    #[serde(rename_all = "camelCase")]
318    AwsSandbox {
319        /// IAM role the image build runs as.
320        build_role_name: String,
321        /// What `egress: deny` needs; absent for an open sandbox.
322        #[serde(default, skip_serializing_if = "Option::is_none")]
323        egress: Option<AwsSandboxEgressScaffolding>,
324        /// A Frozen sandbox's MicroVM image, built during setup. A Live one's image belongs to its
325        /// runtime controller.
326        #[serde(default, skip_serializing_if = "Option::is_none")]
327        image_arn: Option<String>,
328    },
329}
330
331/// The objects that keep an AWS deny sandbox's sessions inside the VPC. Each id is recorded as
332/// soon as the object exists and cleared once it is deleted.
333#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
334#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
335#[serde(rename_all = "camelCase")]
336pub struct AwsSandboxEgressScaffolding {
337    /// IAM role Lambda assumes to place the connector's network interfaces.
338    pub operator_role_name: String,
339    /// Security group permitting egress to loopback only.
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    pub security_group_id: Option<String>,
342    /// `AWS::Lambda::NetworkConnector` the sessions start with.
343    #[serde(default, skip_serializing_if = "Option::is_none")]
344    pub connector_arn: Option<String>,
345    /// Cloud Control request creating or deleting the connector that AWS has not finished. Kept
346    /// so the request's outcome, and AWS's reason when it fails, is read on a later call.
347    #[serde(default, skip_serializing_if = "Option::is_none")]
348    pub connector_request: Option<String>,
349}
350
351impl SetupScaffolding {
352    /// Takes each object `found` names that this record does not, and keeps every one it does:
353    /// a recorded id is what setup last saw, and teardown must delete that one.
354    pub fn fill_missing(&mut self, found: SetupScaffolding) {
355        match (self, found) {
356            (
357                SetupScaffolding::AwsSandbox {
358                    egress, image_arn, ..
359                },
360                SetupScaffolding::AwsSandbox {
361                    egress: found_egress,
362                    image_arn: found_image_arn,
363                    ..
364                },
365            ) => {
366                if image_arn.is_none() {
367                    *image_arn = found_image_arn;
368                }
369                match (egress.as_mut(), found_egress) {
370                    (None, found_egress) => *egress = found_egress,
371                    (Some(recorded), Some(found)) => {
372                        if recorded.security_group_id.is_none() {
373                            recorded.security_group_id = found.security_group_id;
374                        }
375                        if recorded.connector_arn.is_none() {
376                            recorded.connector_arn = found.connector_arn;
377                        }
378                    }
379                    (Some(_), None) => {}
380                }
381            }
382        }
383    }
384}
385
386/// The cross-account read a manager opened on Alien's registry for one deployment.
387#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
388#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
389#[serde(rename_all = "camelCase")]
390pub struct RegistryAccess {
391    /// Repository identifiers the grant names, sorted.
392    #[serde(default, skip_serializing_if = "Vec::is_empty")]
393    pub repositories: Vec<String>,
394
395    /// Compute services the grant admits, sorted. Each pulls as its own principal, so a service
396    /// added later needs the policy rewritten.
397    #[serde(default, skip_serializing_if = "Vec::is_empty")]
398    pub service_types: Vec<String>,
399}
400
401/// Deployment state
402///
403/// Represents the current state of deployed infrastructure, including release tracking.
404/// This is platform-agnostic - no backend IDs or database relationships.
405///
406/// The deployment engine manages releases internally: when a deployment succeeds,
407/// it promotes `target_release` to `current_release` and clears `target_release`.
408#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
409#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
410#[serde(rename_all = "camelCase")]
411pub struct DeploymentState {
412    /// Current lifecycle phase
413    pub status: DeploymentStatus,
414    /// Target cloud platform (AWS, GCP, Azure, Kubernetes)
415    pub platform: Platform,
416    /// Currently deployed release (None for first deployment)
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub current_release: Option<ReleaseInfo>,
419    /// Target release to deploy (None when synced with current)
420    #[serde(skip_serializing_if = "Option::is_none")]
421    pub target_release: Option<ReleaseInfo>,
422    /// Infrastructure resource tracking (which resources exist, their status, outputs)
423    #[serde(skip_serializing_if = "Option::is_none")]
424    pub stack_state: Option<StackState>,
425    /// Deployment-level error for failures not owned by a specific resource.
426    ///
427    /// Resource controller failures belong in `stack_state.resources[*].error`.
428    #[serde(skip_serializing_if = "Option::is_none")]
429    pub error: Option<AlienError>,
430    /// Cloud account details (account ID, project number, region)
431    #[serde(skip_serializing_if = "Option::is_none")]
432    pub environment_info: Option<EnvironmentInfo>,
433    /// Deployment-specific data (prepared stacks, phase tracking, etc.)
434    #[serde(skip_serializing_if = "Option::is_none")]
435    pub runtime_metadata: Option<RuntimeMetadata>,
436    /// Whether a retry has been requested for a failed deployment
437    /// When true and status is a failed state, the deployment system will retry failed resources
438    #[serde(default, skip_serializing_if = "is_false")]
439    pub retry_requested: bool,
440    /// Protocol version for cross-actor compatibility.
441    /// All actors (manager, push client, agent) check this before stepping.
442    /// Mismatched versions produce a clear error instead of silent corruption.
443    /// See docs/02-manager/10-deployment-protocol.md.
444    pub protocol_version: u32,
445}
446
447impl DeploymentState {
448    /// Returns whether this state carries desired infrastructure for the
449    /// deployment runner to converge.
450    pub fn has_desired(&self) -> bool {
451        self.current_release.is_some()
452            || self.target_release.is_some()
453            || self.stack_state.is_some()
454    }
455}
456
457/// Result of a deployment step
458///
459/// Contains the complete next deployment state along with hints for the platform.
460/// This replaces the old delta-based `DeploymentStateUpdate` approach.
461#[derive(Debug, Clone, Serialize, Deserialize)]
462#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
463#[serde(rename_all = "camelCase")]
464pub struct DeploymentStepResult {
465    /// The complete next deployment state
466    pub state: DeploymentState,
467
468    /// Suggested delay before next step (optimization hint)
469    /// - `None`: No suggested delay, can poll immediately
470    /// - `Some(ms)`: Wait this many milliseconds before next step
471    #[serde(skip_serializing_if = "Option::is_none")]
472    pub suggested_delay_ms: Option<u64>,
473
474    /// Whether to update heartbeat timestamp (monitoring signal)
475    /// - `false`: Don't update heartbeat (default for most steps)
476    /// - `true`: Update lastHeartbeatAt (for successful health checks in Running state)
477    #[serde(default, skip_serializing_if = "is_false")]
478    pub update_heartbeat: bool,
479
480    /// Managed Alien resource status samples emitted by controllers during this step.
481    #[serde(
482        default,
483        rename = "resourceHeartbeats",
484        skip_serializing_if = "Vec::is_empty"
485    )]
486    pub heartbeats: Vec<ResourceHeartbeat>,
487
488    /// Observed raw-resource inventory batches read during this step.
489    #[serde(
490        default,
491        rename = "observedInventoryBatches",
492        skip_serializing_if = "Vec::is_empty"
493    )]
494    pub observed_inventory_batches: Vec<ObservedInventoryBatch>,
495}
496
497pub(crate) fn is_false(b: &bool) -> bool {
498    !*b
499}
500
501/// Answers for inputs gating Frozen resources, keyed by input id.
502pub type GateAnswers = IndexMap<String, bool>;
503
504/// Oldest deployment protocol version this binary can read.
505pub const MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 1;
506
507/// Deployment protocol written by actors with resumable protection, CORS and
508/// database update states and retained deletion. Older readers must be fenced
509/// before these states exist.
510pub const CURRENT_DEPLOYMENT_PROTOCOL_VERSION: u32 = 4;
511
512/// Latest state protocol this binary can execute.
513pub const MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 4;
514
515/// GCP federation changes setup ownership and target credential semantics.
516pub const GCP_FEDERATION_DEPLOYMENT_PROTOCOL_VERSION: u32 = 2;
517
518pub fn deployment_protocol_version_for_platform(
519    _platform: crate::Platform,
520    _base_platform: Option<crate::Platform>,
521) -> u32 {
522    CURRENT_DEPLOYMENT_PROTOCOL_VERSION
523}
524
525/// Accept unchanged reports or the explicit upgrade to this writer protocol.
526/// Never permit downgrade or unknown protocols. Provider setup prerequisites
527/// remain separate from this checkpoint compatibility check.
528pub fn accepts_deployment_protocol_report(registered: u32, reported: u32) -> bool {
529    (MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION..=MAX_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION)
530        .contains(&registered)
531        && (reported == registered
532            || (registered < CURRENT_DEPLOYMENT_PROTOCOL_VERSION
533                && reported == CURRENT_DEPLOYMENT_PROTOCOL_VERSION))
534}
535
536/// Backwards-compatible alias for older call sites.
537pub const DEPLOYMENT_PROTOCOL_VERSION: u32 = CURRENT_DEPLOYMENT_PROTOCOL_VERSION;
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542    use crate::{Platform, ReleaseInfo, Stack, StackState};
543    use indexmap::IndexMap;
544
545    fn empty_stack() -> Stack {
546        Stack {
547            id: "stack_test".to_string(),
548            resources: IndexMap::new(),
549            inputs: vec![],
550            dynamic_container_repositories: Vec::new(),
551            dynamic_container_image_resources: Vec::new(),
552            operations: None,
553            permissions: crate::PermissionsConfig::default(),
554            supported_platforms: None,
555        }
556    }
557
558    fn release_info(id: &str) -> ReleaseInfo {
559        ReleaseInfo {
560            release_id: Some(id.to_string()),
561            version: None,
562            description: None,
563            stack: empty_stack(),
564        }
565    }
566
567    fn state() -> DeploymentState {
568        DeploymentState {
569            status: DeploymentStatus::Pending,
570            platform: Platform::Kubernetes,
571            current_release: None,
572            target_release: None,
573            stack_state: None,
574            error: None,
575            environment_info: None,
576            runtime_metadata: None,
577            retry_requested: false,
578            protocol_version: DEPLOYMENT_PROTOCOL_VERSION,
579        }
580    }
581
582    #[test]
583    fn deployment_state_has_desired_when_release_or_stack_state_exists() {
584        let observe_only = state();
585        assert!(!observe_only.has_desired());
586
587        let mut current = state();
588        current.current_release = Some(release_info("rel_current"));
589        assert!(current.has_desired());
590
591        let mut target = state();
592        target.target_release = Some(release_info("rel_target"));
593        assert!(target.has_desired());
594
595        let mut imported = state();
596        imported.stack_state = Some(StackState::new(Platform::Kubernetes));
597        assert!(imported.has_desired());
598    }
599
600    #[test]
601    fn runtime_metadata_from_before_secret_inventory_defaults_to_empty() {
602        let metadata: RuntimeMetadata = serde_json::from_value(serde_json::json!({
603            "lastSyncedEnvVarsHash": "old-hash"
604        }))
605        .expect("old runtime metadata remains readable");
606
607        assert_eq!(
608            metadata.last_synced_env_vars_hash.as_deref(),
609            Some("old-hash")
610        );
611        assert!(metadata.last_synced_secret_names.is_empty());
612        assert!(!metadata.vault_credentials_revoked);
613        assert!(metadata.retained_storage_protection_hash.is_none());
614        assert!(metadata.retained_storage_protection_confirmed_at.is_none());
615        assert!(metadata.pending_prepared_stack.is_none());
616        assert!(metadata.setup_update_authorization.is_none());
617        assert!(metadata.setup_scaffolding.is_empty());
618    }
619
620    /// Teardown reads this record back from persisted state, so its wire form is a contract.
621    #[test]
622    fn setup_scaffolding_round_trips_in_its_persisted_form() {
623        let persisted = serde_json::json!({
624            "initialSetupAuthority": "directSetup",
625            "setupScaffolding": {
626                "agents": { "type": "awsSandbox", "buildRoleName": "acme-agents-build" }
627            }
628        });
629        let metadata: RuntimeMetadata =
630            serde_json::from_value(persisted.clone()).expect("persisted record reads");
631        assert_eq!(
632            metadata.setup_scaffolding["agents"],
633            SetupScaffolding::AwsSandbox {
634                build_role_name: "acme-agents-build".to_string(),
635                egress: None,
636                image_arn: None,
637            }
638        );
639        assert_eq!(metadata.deletion_policy, DeletionPolicy::Retain);
640        let mut expected = persisted;
641        expected["deletionPolicy"] = serde_json::json!("retain");
642        assert_eq!(serde_json::to_value(&metadata).unwrap(), expected);
643        assert!(
644            serde_json::to_value(RuntimeMetadata::default()).unwrap()["setupScaffolding"].is_null(),
645            "state with no scaffolding serializes as it did before the field existed"
646        );
647    }
648
649    #[test]
650    fn filling_a_record_takes_only_what_it_lacks() {
651        let egress = |group: Option<&str>, connector: Option<&str>| AwsSandboxEgressScaffolding {
652            operator_role_name: "acme-agents-egress".to_string(),
653            security_group_id: group.map(str::to_string),
654            connector_arn: connector.map(str::to_string),
655            connector_request: None,
656        };
657        let record = |egress| SetupScaffolding::AwsSandbox {
658            build_role_name: "acme-agents-build".to_string(),
659            egress,
660            image_arn: None,
661        };
662
663        let mut partial = record(Some(egress(Some("sg-recorded"), None)));
664        partial.fill_missing(record(Some(egress(Some("sg-found"), Some("arn:found")))));
665        assert_eq!(
666            partial,
667            record(Some(egress(Some("sg-recorded"), Some("arn:found")))),
668            "a recorded id is the one teardown deletes"
669        );
670
671        let mut role_only = record(None);
672        role_only.fill_missing(record(Some(egress(Some("sg-found"), None))));
673        assert_eq!(role_only, record(Some(egress(Some("sg-found"), None))));
674
675        let image = |arn: Option<&str>| SetupScaffolding::AwsSandbox {
676            build_role_name: "acme-agents-build".to_string(),
677            egress: None,
678            image_arn: arn.map(str::to_string),
679        };
680        let mut without_image = image(None);
681        without_image.fill_missing(image(Some("arn:found")));
682        assert_eq!(without_image, image(Some("arn:found")));
683        let mut with_image = image(Some("arn:recorded"));
684        with_image.fill_missing(image(Some("arn:found")));
685        assert_eq!(with_image, image(Some("arn:recorded")));
686    }
687
688    /// A deny sandbox's record is written piece by piece, so a partial one must read back as is.
689    #[test]
690    fn a_partial_egress_record_round_trips_in_its_persisted_form() {
691        let persisted = serde_json::json!({
692            "type": "awsSandbox",
693            "buildRoleName": "acme-agents-build",
694            "egress": {
695                "operatorRoleName": "acme-agents-egress",
696                "securityGroupId": "sg-0123"
697            }
698        });
699        let record: SetupScaffolding =
700            serde_json::from_value(persisted.clone()).expect("persisted record reads");
701        assert_eq!(
702            record,
703            SetupScaffolding::AwsSandbox {
704                build_role_name: "acme-agents-build".to_string(),
705                egress: Some(AwsSandboxEgressScaffolding {
706                    operator_role_name: "acme-agents-egress".to_string(),
707                    security_group_id: Some("sg-0123".to_string()),
708                    connector_arn: None,
709                    connector_request: None,
710                }),
711                image_arn: None,
712            }
713        );
714        assert_eq!(serde_json::to_value(&record).unwrap(), persisted);
715    }
716}