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};
8
9use super::{DeploymentStatus, EnvironmentInfo, ReleaseInfo};
10
11/// Actor that owns structural work during the initial setup phase.
12#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
13#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
14#[serde(rename_all = "camelCase")]
15pub enum InitialSetupAuthority {
16    /// Setup state was registered by an external setup engine. Alien may only
17    /// continue controller states that the importer explicitly initialized.
18    #[default]
19    ImportedHandoff,
20    /// Alien is the setup engine and is running with administrator credentials.
21    DirectSetup,
22}
23
24/// One-shot authority for a setup re-import to replace setup-owned resources.
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
27#[serde(rename_all = "camelCase")]
28pub struct SetupUpdateAuthorization {
29    /// Unique revision used by persistence layers for compare-and-swap updates.
30    pub nonce: String,
31    /// Frozen resource projection from the last successful deployment.
32    pub baseline_frozen_digest: String,
33    /// Frozen resource projection prepared by the setup re-import.
34    pub target_frozen_digest: String,
35    /// Release whose stack was prepared by setup.
36    pub release_id: String,
37    /// Stable setup target recorded on the imported deployment.
38    pub setup_target: String,
39    /// Exact setup artifact revision that authored this authority.
40    pub setup_fingerprint: String,
41    /// Setup fingerprint contract version.
42    pub setup_fingerprint_version: u32,
43}
44
45/// Runtime metadata for deployment
46///
47/// Stores deployment state that needs to persist across step calls.
48#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
49#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
50#[serde(rename_all = "camelCase")]
51pub struct RuntimeMetadata {
52    /// Actor authorized to perform structural Frozen-resource work during
53    /// InitialSetup. Missing legacy values fail closed as ImportedHandoff.
54    #[serde(default)]
55    pub initial_setup_authority: InitialSetupAuthority,
56
57    /// Hash of the environment variables snapshot that was last synced to the vault
58    /// Used to avoid redundant sync operations during incremental deployment
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub last_synced_env_vars_hash: Option<String>,
61
62    /// Exact vault keys owned by the deployment secret synchronizer. This
63    /// inventory lets a later snapshot delete removed keys without listing or
64    /// touching unrelated values in the same vault.
65    #[serde(default, skip_serializing_if = "Vec::is_empty")]
66    pub last_synced_secret_names: Vec<String>,
67
68    /// The prepared (mutated) stack from the last successful deployment phase
69    /// This is the stack AFTER mutations have been applied (with service accounts, vault, etc.)
70    /// Used for compatibility checks during updates to compare mutated stacks
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub prepared_stack: Option<crate::Stack>,
73
74    /// Canonical resolved answers for inputs that gate Frozen resources,
75    /// keyed by input id, recorded when the deployment is created or its
76    /// setup import registers.
77    ///
78    /// A frozen gate's answer is fixed for the deployment's lifetime: the
79    /// update path refuses input values that conflict with these, and a Live
80    /// resource sharing such an input resolves the persisted answer forever.
81    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
82    pub persisted_gate_answers: GateAnswers,
83
84    /// Prepared target for an update that has not reached Running yet. Keeping
85    /// it separate preserves the last successful baseline across retries.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub pending_prepared_stack: Option<crate::Stack>,
88
89    /// One-shot setup update authority. It contains only non-secret identity
90    /// and canonical resource digests, never the imported payload or tokens.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub setup_update_authorization: Option<SetupUpdateAuthorization>,
93
94    /// Whether cross-account registry access has been successfully granted.
95    /// Set to true after the manager successfully sets the ECR/GAR repo policy
96    /// for this deployment's target account. Prevents redundant API calls on
97    /// every reconcile tick.
98    #[serde(default, skip_serializing_if = "is_false")]
99    pub registry_access_granted: bool,
100}
101
102/// Deployment state
103///
104/// Represents the current state of deployed infrastructure, including release tracking.
105/// This is platform-agnostic - no backend IDs or database relationships.
106///
107/// The deployment engine manages releases internally: when a deployment succeeds,
108/// it promotes `target_release` to `current_release` and clears `target_release`.
109#[derive(Debug, Clone, Serialize, Deserialize, Builder)]
110#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
111#[serde(rename_all = "camelCase")]
112pub struct DeploymentState {
113    /// Current lifecycle phase
114    pub status: DeploymentStatus,
115    /// Target cloud platform (AWS, GCP, Azure, Kubernetes)
116    pub platform: Platform,
117    /// Currently deployed release (None for first deployment)
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub current_release: Option<ReleaseInfo>,
120    /// Target release to deploy (None when synced with current)
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub target_release: Option<ReleaseInfo>,
123    /// Infrastructure resource tracking (which resources exist, their status, outputs)
124    #[serde(skip_serializing_if = "Option::is_none")]
125    pub stack_state: Option<StackState>,
126    /// Deployment-level error for failures not owned by a specific resource.
127    ///
128    /// Resource controller failures belong in `stack_state.resources[*].error`.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub error: Option<AlienError>,
131    /// Cloud account details (account ID, project number, region)
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub environment_info: Option<EnvironmentInfo>,
134    /// Deployment-specific data (prepared stacks, phase tracking, etc.)
135    #[serde(skip_serializing_if = "Option::is_none")]
136    pub runtime_metadata: Option<RuntimeMetadata>,
137    /// Whether a retry has been requested for a failed deployment
138    /// When true and status is a failed state, the deployment system will retry failed resources
139    #[serde(default, skip_serializing_if = "is_false")]
140    pub retry_requested: bool,
141    /// Protocol version for cross-actor compatibility.
142    /// All actors (manager, push client, agent) check this before stepping.
143    /// Mismatched versions produce a clear error instead of silent corruption.
144    /// See docs/02-manager/10-deployment-protocol.md.
145    pub protocol_version: u32,
146}
147
148impl DeploymentState {
149    /// Returns whether this state carries desired infrastructure for the
150    /// deployment runner to converge.
151    pub fn has_desired(&self) -> bool {
152        self.current_release.is_some()
153            || self.target_release.is_some()
154            || self.stack_state.is_some()
155    }
156}
157
158/// Result of a deployment step
159///
160/// Contains the complete next deployment state along with hints for the platform.
161/// This replaces the old delta-based `DeploymentStateUpdate` approach.
162#[derive(Debug, Clone, Serialize, Deserialize)]
163#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
164#[serde(rename_all = "camelCase")]
165pub struct DeploymentStepResult {
166    /// The complete next deployment state
167    pub state: DeploymentState,
168
169    /// Suggested delay before next step (optimization hint)
170    /// - `None`: No suggested delay, can poll immediately
171    /// - `Some(ms)`: Wait this many milliseconds before next step
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub suggested_delay_ms: Option<u64>,
174
175    /// Whether to update heartbeat timestamp (monitoring signal)
176    /// - `false`: Don't update heartbeat (default for most steps)
177    /// - `true`: Update lastHeartbeatAt (for successful health checks in Running state)
178    #[serde(default, skip_serializing_if = "is_false")]
179    pub update_heartbeat: bool,
180
181    /// Managed Alien resource status samples emitted by controllers during this step.
182    #[serde(
183        default,
184        rename = "resourceHeartbeats",
185        skip_serializing_if = "Vec::is_empty"
186    )]
187    pub heartbeats: Vec<ResourceHeartbeat>,
188
189    /// Observed raw-resource inventory batches read during this step.
190    #[serde(
191        default,
192        rename = "observedInventoryBatches",
193        skip_serializing_if = "Vec::is_empty"
194    )]
195    pub observed_inventory_batches: Vec<ObservedInventoryBatch>,
196}
197
198pub(crate) fn is_false(b: &bool) -> bool {
199    !*b
200}
201
202/// Answers for inputs gating Frozen resources, keyed by input id.
203pub type GateAnswers = IndexMap<String, bool>;
204
205/// Oldest deployment protocol version this binary can read.
206pub const MIN_SUPPORTED_DEPLOYMENT_PROTOCOL_VERSION: u32 = 1;
207
208/// Deployment protocol version this binary writes.
209/// Bump when making incompatible changes to DeploymentState semantics.
210///
211/// `persisted_gate_answers` on the runtime metadata stays at this version:
212/// the field is additive, an actor unaware of it still cannot flip a frozen
213/// resource (its strip resolves from state presence, so a changed input is
214/// ignored rather than applied), and the sync routes carry a recorded map
215/// through a write-back that drops the field. A bump would hard-refuse every
216/// customer-scheduled pull agent the moment a newer manager writes state.
217pub const CURRENT_DEPLOYMENT_PROTOCOL_VERSION: u32 = 1;
218
219/// Backwards-compatible alias for older call sites.
220pub const DEPLOYMENT_PROTOCOL_VERSION: u32 = CURRENT_DEPLOYMENT_PROTOCOL_VERSION;
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225    use crate::{Platform, ReleaseInfo, Stack, StackState};
226    use indexmap::IndexMap;
227
228    fn empty_stack() -> Stack {
229        Stack {
230            id: "stack_test".to_string(),
231            resources: IndexMap::new(),
232            inputs: vec![],
233            permissions: crate::PermissionsConfig::default(),
234            supported_platforms: None,
235        }
236    }
237
238    fn release_info(id: &str) -> ReleaseInfo {
239        ReleaseInfo {
240            release_id: Some(id.to_string()),
241            version: None,
242            description: None,
243            stack: empty_stack(),
244        }
245    }
246
247    fn state() -> DeploymentState {
248        DeploymentState {
249            status: DeploymentStatus::Pending,
250            platform: Platform::Kubernetes,
251            current_release: None,
252            target_release: None,
253            stack_state: None,
254            error: None,
255            environment_info: None,
256            runtime_metadata: None,
257            retry_requested: false,
258            protocol_version: DEPLOYMENT_PROTOCOL_VERSION,
259        }
260    }
261
262    #[test]
263    fn deployment_state_has_desired_when_release_or_stack_state_exists() {
264        let observe_only = state();
265        assert!(!observe_only.has_desired());
266
267        let mut current = state();
268        current.current_release = Some(release_info("rel_current"));
269        assert!(current.has_desired());
270
271        let mut target = state();
272        target.target_release = Some(release_info("rel_target"));
273        assert!(target.has_desired());
274
275        let mut imported = state();
276        imported.stack_state = Some(StackState::new(Platform::Kubernetes));
277        assert!(imported.has_desired());
278    }
279
280    #[test]
281    fn runtime_metadata_from_before_secret_inventory_defaults_to_empty() {
282        let metadata: RuntimeMetadata = serde_json::from_value(serde_json::json!({
283            "lastSyncedEnvVarsHash": "old-hash"
284        }))
285        .expect("old runtime metadata remains readable");
286
287        assert_eq!(
288            metadata.last_synced_env_vars_hash.as_deref(),
289            Some("old-hash")
290        );
291        assert!(metadata.last_synced_secret_names.is_empty());
292        assert!(metadata.pending_prepared_stack.is_none());
293        assert!(metadata.setup_update_authorization.is_none());
294    }
295}