Skip to main content

alien_core/
stack_state.rs

1//!
2//! Defines structures for managing the runtime state of deployed resources.
3//! This includes platform-specific internal states, overall stack status,
4//! resource outputs, error tracking, and pending user actions.
5
6use crate::{
7    Platform, Resource, ResourceLifecycle, ResourceOutputs, ResourceOutputsDefinition, ResourceRef,
8    ResourceStatus, ResourceType,
9};
10
11use alien_error::AlienError;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::fmt::Debug;
15use uuid::Uuid;
16
17use crate::{ErrorData, Result};
18
19pub const RESOURCE_PREFIX_ERROR_MESSAGE: &str = "resourcePrefix must be 3-40 characters: lowercase letters, numbers, and hyphens; start with a letter; end with a letter or number; and not contain consecutive hyphens";
20
21pub fn is_valid_resource_prefix(value: &str) -> bool {
22    if !(3..=40).contains(&value.len()) {
23        return false;
24    }
25
26    let mut chars = value.chars();
27    let Some(first) = chars.next() else {
28        return false;
29    };
30    if !first.is_ascii_lowercase() {
31        return false;
32    }
33
34    let Some(last) = value.chars().next_back() else {
35        return false;
36    };
37    if !(last.is_ascii_lowercase() || last.is_ascii_digit()) {
38        return false;
39    }
40
41    let mut previous_was_hyphen = false;
42    for c in value.chars() {
43        if !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') {
44            return false;
45        }
46        if c == '-' && previous_was_hyphen {
47            return false;
48        }
49        previous_was_hyphen = c == '-';
50    }
51
52    true
53}
54
55/// Represents the overall status of a stack based on its resource states.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
58#[serde(rename_all = "snake_case")]
59pub enum StackStatus {
60    /// Stack is initializing with no resources yet created
61    Pending,
62    /// Stack has resources that are currently being provisioned, updated, or deleted
63    InProgress,
64    /// All resources are successfully running and the stack is operational
65    Running,
66    /// All resources have been successfully deleted and the stack is removed
67    Deleted,
68    /// One or more resources have failed during provisioning, updating, or deleting
69    Failure,
70}
71
72/// Represents the collective state of all resources in a stack, including platform and pending actions.
73#[derive(Debug, Clone, Serialize, Deserialize)]
74#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
75#[serde(rename_all = "camelCase")]
76pub struct StackState {
77    /// The target platform for this stack state.
78    pub platform: Platform,
79    /// The state of individual resources, keyed by resource ID.
80    pub resources: HashMap<String, StackResourceState>,
81    /// A prefix used for resource naming to ensure uniqueness across deployments.
82    pub resource_prefix: String,
83}
84
85impl StackState {
86    /// Creates a new, empty StackState for a given platform with a generated resource prefix.
87    pub fn new(platform: Platform) -> Self {
88        // Generate a resource prefix that matches [a-zA-Z][a-zA-Z\d\-]*[a-zA-Z\d] pattern
89        // (e.g., "k44e9b72", "m8a3f1d5")
90        let letters = "abcdefghijklmnopqrstuvwxyz";
91        let first_char = letters
92            .chars()
93            .nth(Uuid::new_v4().as_bytes()[0] as usize % 26)
94            .unwrap();
95        let uuid_part = Uuid::new_v4().simple().to_string()[..7].to_string();
96        let prefix = format!("{}{}", first_char, uuid_part);
97
98        StackState {
99            platform,
100            resources: HashMap::new(),
101            resource_prefix: prefix,
102        }
103    }
104
105    /// Creates an empty StackState for resources whose physical prefix was
106    /// already chosen by an external setup artifact.
107    pub fn with_resource_prefix(platform: Platform, resource_prefix: String) -> Self {
108        StackState {
109            platform,
110            resources: HashMap::new(),
111            resource_prefix,
112        }
113    }
114
115    /// Returns a reference to the state of a specific resource if it exists.
116    pub fn resource(&self, id: &str) -> Option<&StackResourceState> {
117        self.resources.get(id)
118    }
119
120    /// Computes the stack status from the current resource statuses.
121    /// This is the main function that implements the logic from the TypeScript version.
122    pub fn compute_stack_status(&self) -> Result<StackStatus> {
123        let resource_statuses: Vec<ResourceStatus> = self
124            .resources
125            .values()
126            .map(|resource| resource.status)
127            .collect();
128
129        Self::compute_stack_status_from_resources(&resource_statuses)
130    }
131
132    /// Static method to compute stack status from a list of resource statuses.
133    /// This method contains the core logic and can be tested independently.
134    pub fn compute_stack_status_from_resources(
135        resource_statuses: &[ResourceStatus],
136    ) -> Result<StackStatus> {
137        // If there are no resources, it's pending (initializing a completely new stack state)
138        if resource_statuses.is_empty() {
139            return Ok(StackStatus::Pending);
140        }
141
142        // Check for any failure states
143        if resource_statuses.iter().any(|status| {
144            matches!(
145                status,
146                ResourceStatus::ProvisionFailed
147                    | ResourceStatus::UpdateFailed
148                    | ResourceStatus::DeleteFailed
149                    | ResourceStatus::RefreshFailed
150            )
151        }) {
152            return Ok(StackStatus::Failure);
153        }
154
155        // Check for any in-progress states
156        if resource_statuses.iter().any(|status| {
157            matches!(
158                status,
159                ResourceStatus::Pending
160                    | ResourceStatus::Provisioning
161                    | ResourceStatus::Updating
162                    | ResourceStatus::Deleting
163                    | ResourceStatus::TeardownRequired
164            )
165        }) {
166            return Ok(StackStatus::InProgress);
167        }
168
169        // Check for terminal states
170        if resource_statuses
171            .iter()
172            .all(|status| matches!(status, ResourceStatus::Running))
173        {
174            return Ok(StackStatus::Running);
175        }
176
177        if resource_statuses
178            .iter()
179            .all(|status| matches!(status, ResourceStatus::Deleted))
180        {
181            return Ok(StackStatus::Deleted);
182        }
183
184        // Check for mixed Running + Deleted (deletion in progress)
185        // This happens during dependency-ordered deletion when some resources are deleted
186        // but others are still running while waiting for dependencies to clear
187        let has_running = resource_statuses
188            .iter()
189            .any(|status| matches!(status, ResourceStatus::Running));
190        let has_deleted = resource_statuses
191            .iter()
192            .any(|status| matches!(status, ResourceStatus::Deleted));
193        let only_running_or_deleted = resource_statuses
194            .iter()
195            .all(|status| matches!(status, ResourceStatus::Running | ResourceStatus::Deleted));
196
197        if has_running && has_deleted && only_running_or_deleted {
198            return Ok(StackStatus::InProgress);
199        }
200
201        // Mixed terminal states or unexpected combinations
202        let status_strings: Vec<String> = resource_statuses
203            .iter()
204            .map(|status| format!("{:?}", status).to_lowercase().replace('_', "-"))
205            .collect();
206
207        Err(AlienError::new(
208            ErrorData::UnexpectedResourceStatusCombination {
209                resource_statuses: status_strings,
210                operation: "stack status computation".to_string(),
211            },
212        ))
213    }
214
215    /// Retrieves and downcasts the outputs of a resource from the stack state.
216    ///
217    /// # Arguments
218    /// * `resource_id` - The ID of the resource to get outputs for
219    ///
220    /// # Returns
221    /// * `Ok(T)` - The downcasted outputs if successful
222    /// * `Err(Error)` - If the resource doesn't exist, has no outputs, or the outputs are not of the expected type
223    ///
224    /// # Example
225    /// ```rust,ignore
226    /// use alien_core::{StackState, Platform, WorkerOutputs};
227    ///
228    /// let stack_state = StackState::new(Platform::Aws);
229    ///
230    /// // Get worker outputs with error handling
231    /// let worker_outputs = stack_state.get_resource_outputs::<WorkerOutputs>("my-worker")?;
232    /// if let Some(url) = &worker_outputs.url {
233    ///     println!("Worker URL: {}", url);
234    /// }
235    /// ```
236    pub fn get_resource_outputs<T: ResourceOutputsDefinition + 'static>(
237        &self,
238        resource_id: &str,
239    ) -> Result<&T> {
240        let resource_state = self.resources.get(resource_id).ok_or_else(|| {
241            AlienError::new(ErrorData::ResourceNotFound {
242                resource_id: resource_id.to_string(),
243                available_resources: self.resources.keys().cloned().collect(),
244            })
245        })?;
246
247        let outputs = resource_state.outputs.as_ref().ok_or_else(|| {
248            AlienError::new(ErrorData::ResourceHasNoOutputs {
249                resource_id: resource_id.to_string(),
250            })
251        })?;
252
253        outputs.downcast_ref::<T>().ok_or_else(|| {
254            AlienError::new(ErrorData::UnexpectedResourceType {
255                resource_id: resource_id.to_string(),
256                expected: ResourceType::from_static(std::any::type_name::<T>()),
257                actual: resource_state.resource_type.clone().into(),
258            })
259        })
260    }
261}
262
263/// Represents the state of a single resource within the stack for a specific platform.
264#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
265#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
266#[serde(rename_all = "camelCase")]
267pub struct StackResourceState {
268    /// The high-level type of the resource (e.g., Worker::RESOURCE_TYPE, Storage::RESOURCE_TYPE).
269    #[serde(rename = "type")]
270    pub resource_type: String,
271
272    /// The platform-specific resource controller that manages this resource's lifecycle.
273    /// This is None when the resource status is Pending.
274    /// Stored as JSON to make the struct serializable and movable to alien-core.
275    #[serde(rename = "_internal", skip_serializing_if = "Option::is_none")]
276    pub internal_state: Option<serde_json::Value>,
277
278    /// High-level status derived from the internal state.
279    pub status: ResourceStatus,
280
281    /// Presentation metadata from the effective resource entry, outside runtime configuration.
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub display_name: Option<String>,
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub description: Option<String>,
286
287    /// Last reported step explanation for display only; not a machine-readable status.
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub progress: Option<String>,
290
291    /// Outputs generated by the resource (e.g., ARN, URL, Bucket Name).
292    #[serde(skip_serializing_if = "Option::is_none")]
293    pub outputs: Option<ResourceOutputs>,
294
295    /// The current resource configuration.
296    pub config: Resource,
297
298    /// The previous resource configuration during updates.
299    /// This is set when an update is initiated and cleared when the update completes or fails.
300    #[serde(skip_serializing_if = "Option::is_none")]
301    pub previous_config: Option<Resource>,
302
303    /// Tracks consecutive retry attempts for the current state transition.
304    #[serde(default, skip_serializing_if = "is_zero")]
305    #[builder(default)]
306    pub retry_attempt: u32,
307
308    /// Stores the last error encountered during a failed step transition.
309    #[serde(skip_serializing_if = "Option::is_none")]
310    pub error: Option<AlienError>,
311
312    /// The lifecycle of the resource (Frozen or Live).
313    /// Defaults to Live if not specified.
314    #[serde(skip_serializing_if = "Option::is_none")]
315    pub lifecycle: Option<ResourceLifecycle>,
316
317    /// Platform whose controller owns this resource state. Defaults to the
318    /// containing stack platform when absent.
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub controller_platform: Option<Platform>,
321
322    /// Complete list of dependencies for this resource, including infrastructure dependencies.
323    /// This preserves the full dependency information from the stack definition.
324    #[serde(default, skip_serializing_if = "Vec::is_empty")]
325    #[builder(default = vec![])]
326    pub dependencies: Vec<ResourceRef>,
327
328    /// Stores the controller state that failed, used for manual retry operations.
329    /// This allows resuming from the exact point where the failure occurred.
330    /// Stored as JSON to make the struct serializable and movable to alien-core.
331    #[serde(skip_serializing_if = "Option::is_none")]
332    pub last_failed_state: Option<serde_json::Value>,
333
334    /// Binding parameters for remote access.
335    /// Only populated when the resource has `remote_access: true` in its ResourceEntry.
336    /// This is the JSON serialization of the binding configuration (e.g., StorageBinding, VaultBinding).
337    /// Populated by controllers during provisioning using get_binding_params().
338    #[serde(skip_serializing_if = "Option::is_none")]
339    pub remote_binding_params: Option<serde_json::Value>,
340
341    /// Whether this resource was adopted from an external binding instead of provisioned.
342    /// The binding may exist only where the adopting executor ran (a Helm value or a
343    /// chart-created database), so the record carries it: deleting the resource releases it
344    /// and never touches what the binding points at.
345    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
346    #[builder(default)]
347    pub external_binding: bool,
348
349    /// Whether this resource owes an update because a dependency is changing, though its own
350    /// config is not. The update waits until the dependency has rolled to the release being
351    /// applied, so the owed update must survive between plans and restarts. Cleared when the
352    /// update starts. State written before this field existed reads as not owing one.
353    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
354    #[builder(default)]
355    pub dependency_update_pending: bool,
356
357    /// The rollout in which an update ran because the controller asked for one while the
358    /// config was unchanged. While the controller keeps asking in that same rollout, its
359    /// dependents no longer wait for it, so a check that never settles cannot hold them back
360    /// for good. A later rollout is a new request and is waited for again. Cleared once the
361    /// controller stops asking. State written before this field existed (it was a flag then)
362    /// reads as none.
363    #[serde(
364        default,
365        skip_serializing_if = "Option::is_none",
366        deserialize_with = "deserialize_requested_update_rollout"
367    )]
368    pub requested_update_ran: Option<String>,
369}
370
371/// Reads the rollout identity, treating anything else (the flag older state held) as none.
372fn deserialize_requested_update_rollout<'de, D>(
373    deserializer: D,
374) -> std::result::Result<Option<String>, D::Error>
375where
376    D: serde::Deserializer<'de>,
377{
378    let value = <Option<serde_json::Value> as serde::Deserialize>::deserialize(deserializer)?;
379    Ok(match value {
380        Some(serde_json::Value::String(rollout)) => Some(rollout),
381        _ => None,
382    })
383}
384
385impl StackResourceState {
386    /// Creates a new pending StackResourceState for a resource that's about to be created
387    pub fn new_pending(
388        resource_type: String,
389        config: Resource,
390        lifecycle: Option<ResourceLifecycle>,
391        dependencies: Vec<ResourceRef>,
392    ) -> Self {
393        Self {
394            resource_type,
395            internal_state: None,
396            status: ResourceStatus::Pending,
397            progress: None,
398            display_name: None,
399            description: None,
400            outputs: None,
401            config,
402            previous_config: None,
403            retry_attempt: 0,
404            error: None,
405            lifecycle,
406            controller_platform: None,
407            dependencies,
408            last_failed_state: None,
409            remote_binding_params: None,
410            external_binding: false,
411            dependency_update_pending: false,
412            requested_update_ran: None,
413        }
414    }
415
416    /// Creates a new StackResourceState based on this one, with only the specified fields modified
417    pub fn with_updates<F>(&self, update_fn: F) -> Self
418    where
419        F: FnOnce(&mut Self),
420    {
421        let mut new_state = self.clone();
422        update_fn(&mut new_state);
423        new_state
424    }
425
426    /// Creates a new StackResourceState with the status changed to a failure state and error set
427    pub fn with_failure(&self, status: ResourceStatus, error: AlienError) -> Self {
428        self.with_updates(|state| {
429            state.status = status;
430            state.progress = None;
431            state.error = Some(error);
432            state.retry_attempt = 0;
433        })
434    }
435}
436
437// Helper function for skip_serializing_if on retry_attempt
438fn is_zero(num: &u32) -> bool {
439    *num == 0
440}
441
442#[cfg(test)]
443mod tests {
444    use super::*;
445    use crate::{
446        ExposeProtocol, PublicEndpointOutput, ResourceType, Storage, StorageOutputs, Worker,
447        WorkerCode, WorkerOutputs,
448    };
449
450    /// State saved before `dependencyUpdatePending` existed reads as owing no update, and the
451    /// field stays out of the saved form while it is false.
452    #[test]
453    fn a_resource_state_saved_without_the_pending_marker_reads_as_not_owing_an_update() {
454        let saved = serde_json::json!({
455            "type": "storage",
456            "status": "running",
457            "config": { "type": "storage", "id": "data" },
458        });
459        let state: StackResourceState = serde_json::from_value(saved).unwrap();
460        assert!(!state.dependency_update_pending);
461        assert!(serde_json::to_value(&state)
462            .unwrap()
463            .get("dependencyUpdatePending")
464            .is_none());
465
466        let mut owing = state;
467        owing.dependency_update_pending = true;
468        let round_trip: StackResourceState =
469            serde_json::from_value(serde_json::to_value(&owing).unwrap()).unwrap();
470        assert!(round_trip.dependency_update_pending);
471    }
472
473    /// State saved before `requestedUpdateRan` existed, or while it was a flag, reads as no
474    /// rollout having run it, and the field stays out of the saved form while it is none.
475    #[test]
476    fn a_resource_state_saved_without_the_requested_update_record_reads_as_none_ran() {
477        let saved = serde_json::json!({
478            "type": "storage",
479            "status": "running",
480            "config": { "type": "storage", "id": "data" },
481        });
482        let state: StackResourceState = serde_json::from_value(saved).unwrap();
483        assert!(state.requested_update_ran.is_none());
484        assert!(serde_json::to_value(&state)
485            .unwrap()
486            .get("requestedUpdateRan")
487            .is_none());
488
489        for flag in [true, false] {
490            let saved_flag = serde_json::json!({
491                "type": "storage",
492                "status": "running",
493                "config": { "type": "storage", "id": "data" },
494                "requestedUpdateRan": flag,
495            });
496            let state: StackResourceState = serde_json::from_value(saved_flag).unwrap();
497            assert!(state.requested_update_ran.is_none());
498        }
499
500        let mut ran = state;
501        ran.requested_update_ran = Some("rel_a".to_string());
502        let saved_after = serde_json::to_value(&ran).unwrap();
503        assert_eq!(
504            saved_after["requestedUpdateRan"],
505            serde_json::json!("rel_a")
506        );
507        let round_trip: StackResourceState = serde_json::from_value(saved_after).unwrap();
508        assert_eq!(round_trip.requested_update_ran.as_deref(), Some("rel_a"));
509    }
510
511    #[test]
512    fn resource_prefix_validation_accepts_canonical_prefixes() {
513        for prefix in ["abc", "a-b", "acme-prod", "a1-b2-c3", "a1234567890"] {
514            assert!(is_valid_resource_prefix(prefix), "{prefix}");
515        }
516    }
517
518    #[test]
519    fn resource_prefix_validation_rejects_non_canonical_prefixes() {
520        for prefix in [
521            "",
522            "ab",
523            "a-",
524            "-ab",
525            "Aab",
526            "a_b",
527            "a--b",
528            "a.b",
529            "a1234567890123456789012345678901234567890",
530        ] {
531            assert!(!is_valid_resource_prefix(prefix), "{prefix}");
532        }
533    }
534
535    #[test]
536    fn test_get_resource_outputs_success() {
537        let mut stack_state = StackState::new(Platform::Aws);
538
539        // Create a worker with outputs
540        let worker_outputs = WorkerOutputs {
541            worker_name: "test-worker".to_string(),
542            public_endpoints: HashMap::from([(
543                "api".to_string(),
544                PublicEndpointOutput {
545                    url: "https://example.lambda-url.us-east-1.on.aws/".to_string(),
546                    host: "example.lambda-url.us-east-1.on.aws".to_string(),
547                    protocol: ExposeProtocol::Http,
548                    port: 443,
549                    wildcard_host: None,
550                    load_balancer_endpoint: None,
551                },
552            )]),
553            identifier: Some(
554                "arn:aws:lambda:us-east-1:123456789012:function:test-worker".to_string(),
555            ),
556            commands_push_target: None,
557        };
558
559        let test_worker = Worker::new("test-worker".to_string())
560            .code(WorkerCode::Image {
561                image: "test:latest".to_string(),
562            })
563            .permissions("test-profile".to_string())
564            .build();
565
566        let resource_state = StackResourceState::new_pending(
567            "worker".to_string(),
568            Resource::new(test_worker),
569            None,
570            Vec::new(),
571        )
572        .with_updates(|state| {
573            state.status = ResourceStatus::Running;
574            state.outputs = Some(ResourceOutputs::new(worker_outputs.clone()));
575        });
576
577        stack_state
578            .resources
579            .insert("test-worker".to_string(), resource_state);
580
581        // Test successful retrieval
582        let retrieved_outputs = stack_state
583            .get_resource_outputs::<WorkerOutputs>("test-worker")
584            .unwrap();
585        assert_eq!(retrieved_outputs.worker_name, "test-worker");
586        assert_eq!(
587            retrieved_outputs.public_endpoints["api"].url,
588            "https://example.lambda-url.us-east-1.on.aws/"
589        );
590        assert_eq!(
591            retrieved_outputs.identifier,
592            Some("arn:aws:lambda:us-east-1:123456789012:function:test-worker".to_string())
593        );
594    }
595
596    #[test]
597    fn test_get_resource_outputs_resource_not_found() {
598        let stack_state = StackState::new(Platform::Aws);
599
600        // Test resource not found
601        let result = stack_state.get_resource_outputs::<WorkerOutputs>("nonexistent-worker");
602        assert!(result.is_err());
603        let error = result.unwrap_err();
604
605        // Assert on the specific error variant
606        let error_data = &error.error;
607        if let Some(ErrorData::ResourceNotFound {
608            resource_id,
609            available_resources,
610        }) = error_data
611        {
612            assert_eq!(resource_id, "nonexistent-worker");
613            assert_eq!(available_resources, &Vec::<String>::new());
614        } else {
615            panic!("Expected ResourceNotFound error, got: {:?}", error_data);
616        }
617
618        // Also check the string representation
619        let error_message = error.to_string();
620        assert!(error_message.contains("Resource 'nonexistent-worker' not found in stack state"));
621        assert!(error_message.contains("Available resources: []"));
622    }
623
624    #[test]
625    fn test_get_resource_outputs_no_outputs() {
626        let mut stack_state = StackState::new(Platform::Aws);
627
628        // Create a resource without outputs
629        let test_worker_2 = Worker::new("test-worker".to_string())
630            .code(WorkerCode::Image {
631                image: "test:latest".to_string(),
632            })
633            .permissions("test-profile".to_string())
634            .build();
635
636        let resource_state = StackResourceState::new_pending(
637            "worker".to_string(),
638            Resource::new(test_worker_2),
639            None,
640            Vec::new(),
641        )
642        .with_updates(|state| {
643            state.status = ResourceStatus::Provisioning;
644        });
645
646        stack_state
647            .resources
648            .insert("test-worker".to_string(), resource_state);
649
650        // Test no outputs
651        let result = stack_state.get_resource_outputs::<WorkerOutputs>("test-worker");
652        assert!(result.is_err());
653        let error = result.unwrap_err();
654
655        // Assert on the specific error variant
656        let error_data = &error.error;
657        if let Some(ErrorData::ResourceHasNoOutputs { resource_id, .. }) = error_data {
658            assert_eq!(resource_id, "test-worker");
659        } else {
660            panic!("Expected ResourceHasNoOutputs error, got: {:?}", error_data);
661        }
662
663        // Also check the string representation
664        let error_message = error.to_string();
665        assert!(error_message.contains("Resource 'test-worker' has no outputs"));
666    }
667
668    #[test]
669    fn test_get_resource_outputs_wrong_type() {
670        let mut stack_state = StackState::new(Platform::Aws);
671
672        // Create a storage resource with storage outputs
673        let storage_outputs = StorageOutputs {
674            bucket_name: "test-bucket".to_string(),
675        };
676
677        let test_storage = Storage::new("test-storage".to_string()).build();
678
679        let resource_state = StackResourceState::new_pending(
680            "storage".to_string(),
681            Resource::new(test_storage),
682            None,
683            Vec::new(),
684        )
685        .with_updates(|state| {
686            state.status = ResourceStatus::Running;
687            state.outputs = Some(ResourceOutputs::new(storage_outputs));
688        });
689
690        stack_state
691            .resources
692            .insert("test-storage".to_string(), resource_state);
693
694        // Try to get worker outputs from a storage resource
695        let result = stack_state.get_resource_outputs::<WorkerOutputs>("test-storage");
696        assert!(result.is_err());
697        let error = result.unwrap_err();
698
699        // Assert on the specific error variant
700        let error_data = &error.error;
701        if let Some(ErrorData::UnexpectedResourceType {
702            resource_id,
703            expected,
704            actual,
705        }) = error_data
706        {
707            assert_eq!(resource_id, "test-storage");
708            assert!(
709                expected.0.contains("WorkerOutputs"),
710                "expected should reference WorkerOutputs, got: {}",
711                expected.0
712            );
713            assert_eq!(*actual, ResourceType::from_static("storage"));
714        } else {
715            panic!(
716                "Expected UnexpectedResourceType error, got: {:?}",
717                error_data
718            );
719        }
720    }
721
722    #[test]
723    fn test_get_resource_outputs_usage_example() {
724        let mut stack_state = StackState::new(Platform::Aws);
725
726        // Create a worker with outputs (similar to your original sketch)
727        let worker_outputs = WorkerOutputs {
728            worker_name: "test-alien-worker".to_string(),
729            public_endpoints: HashMap::from([(
730                "api".to_string(),
731                PublicEndpointOutput {
732                    url: "https://test.lambda-url.us-east-1.on.aws/".to_string(),
733                    host: "test.lambda-url.us-east-1.on.aws".to_string(),
734                    protocol: ExposeProtocol::Http,
735                    port: 443,
736                    wildcard_host: None,
737                    load_balancer_endpoint: None,
738                },
739            )]),
740            identifier: Some(
741                "arn:aws:lambda:us-east-1:123456789012:function:test-alien-worker".to_string(),
742            ),
743            commands_push_target: None,
744        };
745
746        let test_alien_worker = Worker::new("test-alien-worker".to_string())
747            .code(WorkerCode::Image {
748                image: "test:latest".to_string(),
749            })
750            .permissions("test-profile".to_string())
751            .build();
752
753        let resource_state = StackResourceState {
754            progress: None,
755            display_name: None,
756            description: None,
757            resource_type: "worker".to_string(),
758            internal_state: None,
759            status: ResourceStatus::Running,
760            outputs: Some(ResourceOutputs::new(worker_outputs)),
761            config: Resource::new(test_alien_worker),
762            previous_config: None,
763            retry_attempt: 0,
764            error: None,
765            lifecycle: None,
766            dependencies: Vec::new(),
767            last_failed_state: None,
768            remote_binding_params: None,
769            controller_platform: None,
770            external_binding: false,
771            dependency_update_pending: false,
772            requested_update_ran: None,
773        };
774
775        stack_state
776            .resources
777            .insert("test-alien-worker".to_string(), resource_state);
778
779        // Test the usage pattern from your original sketch
780        let worker_outputs = stack_state
781            .get_resource_outputs::<WorkerOutputs>("test-alien-worker")
782            .unwrap();
783
784        let worker_url = &worker_outputs
785            .public_endpoints
786            .get("api")
787            .ok_or_else(|| "Worker API endpoint not found in stack state")
788            .unwrap()
789            .url;
790
791        assert_eq!(worker_url, "https://test.lambda-url.us-east-1.on.aws/");
792    }
793
794    /// Records written before adoption was recorded read as not bound, and a record that isn't
795    /// bound serializes exactly as before, so its synced state and hashes don't change.
796    #[test]
797    fn binding_adoption_is_recorded_without_changing_unbound_records() {
798        let written_before = serde_json::json!({
799            "type": "postgres",
800            "status": "running",
801            "config": {"type": "postgres", "id": "database", "version": "17", "storage": "20Gi", "highAvailability": false},
802            "lifecycle": "frozen"
803        });
804        let mut state: StackResourceState = serde_json::from_value(written_before.clone()).unwrap();
805        assert!(!state.external_binding);
806        assert_eq!(serde_json::to_value(&state).unwrap(), written_before);
807
808        state.external_binding = true;
809        let recorded = serde_json::to_value(&state).unwrap();
810        assert_eq!(recorded["externalBinding"], serde_json::json!(true));
811        let read_back: StackResourceState = serde_json::from_value(recorded).unwrap();
812        assert!(read_back.external_binding);
813    }
814
815    // Tests for StackStatus computation - ported from TypeScript
816    #[cfg(test)]
817    mod stack_status_tests {
818        use super::*;
819
820        #[test]
821        fn test_compute_stack_status_empty_resources() {
822            let result = StackState::compute_stack_status_from_resources(&[]).unwrap();
823            assert_eq!(result, StackStatus::Pending);
824        }
825
826        #[test]
827        fn test_compute_stack_status_single_pending() {
828            let result =
829                StackState::compute_stack_status_from_resources(&[ResourceStatus::Pending])
830                    .unwrap();
831            assert_eq!(result, StackStatus::InProgress);
832        }
833
834        #[test]
835        fn test_compute_stack_status_single_provisioning() {
836            let result =
837                StackState::compute_stack_status_from_resources(&[ResourceStatus::Provisioning])
838                    .unwrap();
839            assert_eq!(result, StackStatus::InProgress);
840        }
841
842        #[test]
843        fn test_compute_stack_status_single_updating() {
844            let result =
845                StackState::compute_stack_status_from_resources(&[ResourceStatus::Updating])
846                    .unwrap();
847            assert_eq!(result, StackStatus::InProgress);
848        }
849
850        #[test]
851        fn test_compute_stack_status_single_deleting() {
852            let result =
853                StackState::compute_stack_status_from_resources(&[ResourceStatus::Deleting])
854                    .unwrap();
855            assert_eq!(result, StackStatus::InProgress);
856        }
857
858        #[test]
859        fn test_compute_stack_status_single_provision_failed() {
860            let result =
861                StackState::compute_stack_status_from_resources(&[ResourceStatus::ProvisionFailed])
862                    .unwrap();
863            assert_eq!(result, StackStatus::Failure);
864        }
865
866        #[test]
867        fn test_compute_stack_status_single_update_failed() {
868            let result =
869                StackState::compute_stack_status_from_resources(&[ResourceStatus::UpdateFailed])
870                    .unwrap();
871            assert_eq!(result, StackStatus::Failure);
872        }
873
874        #[test]
875        fn test_compute_stack_status_single_delete_failed() {
876            let result =
877                StackState::compute_stack_status_from_resources(&[ResourceStatus::DeleteFailed])
878                    .unwrap();
879            assert_eq!(result, StackStatus::Failure);
880        }
881
882        #[test]
883        fn test_compute_stack_status_single_refresh_failed() {
884            let result =
885                StackState::compute_stack_status_from_resources(&[ResourceStatus::RefreshFailed])
886                    .unwrap();
887            assert_eq!(result, StackStatus::Failure);
888        }
889
890        #[test]
891        fn test_compute_stack_status_single_running() {
892            let result =
893                StackState::compute_stack_status_from_resources(&[ResourceStatus::Running])
894                    .unwrap();
895            assert_eq!(result, StackStatus::Running);
896        }
897
898        #[test]
899        fn test_compute_stack_status_single_deleted() {
900            let result =
901                StackState::compute_stack_status_from_resources(&[ResourceStatus::Deleted])
902                    .unwrap();
903            assert_eq!(result, StackStatus::Deleted);
904        }
905
906        #[test]
907        fn test_compute_stack_status_all_running() {
908            let statuses = vec![
909                ResourceStatus::Running,
910                ResourceStatus::Running,
911                ResourceStatus::Running,
912            ];
913            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
914            assert_eq!(result, StackStatus::Running);
915        }
916
917        #[test]
918        fn test_compute_stack_status_all_deleted() {
919            let statuses = vec![
920                ResourceStatus::Deleted,
921                ResourceStatus::Deleted,
922                ResourceStatus::Deleted,
923            ];
924            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
925            assert_eq!(result, StackStatus::Deleted);
926        }
927
928        #[test]
929        fn test_compute_stack_status_all_pending() {
930            let statuses = vec![
931                ResourceStatus::Pending,
932                ResourceStatus::Pending,
933                ResourceStatus::Pending,
934            ];
935            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
936            assert_eq!(result, StackStatus::InProgress);
937        }
938
939        #[test]
940        fn test_compute_stack_status_all_provisioning() {
941            let statuses = vec![
942                ResourceStatus::Provisioning,
943                ResourceStatus::Provisioning,
944                ResourceStatus::Provisioning,
945            ];
946            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
947            assert_eq!(result, StackStatus::InProgress);
948        }
949
950        #[test]
951        fn test_compute_stack_status_all_provision_failed() {
952            let statuses = vec![
953                ResourceStatus::ProvisionFailed,
954                ResourceStatus::ProvisionFailed,
955                ResourceStatus::ProvisionFailed,
956            ];
957            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
958            assert_eq!(result, StackStatus::Failure);
959        }
960
961        #[test]
962        fn test_compute_stack_status_mixed_with_failure() {
963            let statuses = vec![
964                ResourceStatus::Running,
965                ResourceStatus::ProvisionFailed,
966                ResourceStatus::Updating,
967            ];
968            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
969            assert_eq!(result, StackStatus::Failure);
970        }
971
972        #[test]
973        fn test_compute_stack_status_failure_with_success() {
974            let statuses = vec![
975                ResourceStatus::Running,
976                ResourceStatus::UpdateFailed,
977                ResourceStatus::Running,
978            ];
979            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
980            assert_eq!(result, StackStatus::Failure);
981        }
982
983        #[test]
984        fn test_compute_stack_status_failure_with_in_progress() {
985            let statuses = vec![
986                ResourceStatus::Provisioning,
987                ResourceStatus::DeleteFailed,
988                ResourceStatus::Deleting,
989            ];
990            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
991            assert_eq!(result, StackStatus::Failure);
992        }
993
994        #[test]
995        fn test_compute_stack_status_any_in_progress() {
996            let statuses = vec![
997                ResourceStatus::Running,
998                ResourceStatus::Updating,
999                ResourceStatus::Running,
1000            ];
1001            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
1002            assert_eq!(result, StackStatus::InProgress);
1003        }
1004
1005        #[test]
1006        fn test_compute_stack_status_mixed_in_progress_states() {
1007            let statuses = vec![
1008                ResourceStatus::Pending,
1009                ResourceStatus::Provisioning,
1010                ResourceStatus::Updating,
1011                ResourceStatus::Deleting,
1012            ];
1013            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
1014            assert_eq!(result, StackStatus::InProgress);
1015        }
1016
1017        #[test]
1018        fn test_compute_stack_status_deletion_in_progress() {
1019            // During deletion, some resources are deleted while others are still running
1020            // (waiting for dependencies to clear). This should be InProgress, not an error.
1021            let statuses = vec![ResourceStatus::Running, ResourceStatus::Deleted];
1022            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
1023            assert_eq!(result, StackStatus::InProgress);
1024        }
1025
1026        #[test]
1027        fn test_compute_stack_status_deletion_in_progress_many_resources() {
1028            // Test with a more realistic scenario: 9 resources, 2 deleted, 7 still running
1029            let statuses = vec![
1030                ResourceStatus::Running,
1031                ResourceStatus::Running,
1032                ResourceStatus::Deleted,
1033                ResourceStatus::Deleted,
1034                ResourceStatus::Running,
1035                ResourceStatus::Running,
1036                ResourceStatus::Running,
1037                ResourceStatus::Running,
1038                ResourceStatus::Running,
1039            ];
1040            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
1041            assert_eq!(result, StackStatus::InProgress);
1042        }
1043
1044        #[test]
1045        fn test_compute_stack_status_mixed_terminal_with_in_progress() {
1046            let statuses = vec![
1047                ResourceStatus::Running,
1048                ResourceStatus::Deleted,
1049                ResourceStatus::Pending,
1050            ];
1051            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
1052            assert_eq!(result, StackStatus::InProgress);
1053        }
1054
1055        #[test]
1056        fn test_compute_stack_status_large_number_of_resources() {
1057            let statuses: Vec<ResourceStatus> = (0..100).map(|_| ResourceStatus::Running).collect();
1058            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
1059            assert_eq!(result, StackStatus::Running);
1060        }
1061
1062        #[test]
1063        fn test_compute_stack_status_single_failure_among_many() {
1064            let mut statuses: Vec<ResourceStatus> =
1065                (0..50).map(|_| ResourceStatus::Running).collect();
1066            statuses.push(ResourceStatus::ProvisionFailed);
1067            statuses.extend((0..49).map(|_| ResourceStatus::Provisioning));
1068
1069            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
1070            assert_eq!(result, StackStatus::Failure);
1071        }
1072
1073        #[test]
1074        fn test_compute_stack_status_failure_priority_over_in_progress() {
1075            let statuses = vec![
1076                ResourceStatus::ProvisionFailed,
1077                ResourceStatus::UpdateFailed,
1078                ResourceStatus::DeleteFailed,
1079                ResourceStatus::Provisioning,
1080                ResourceStatus::Updating,
1081                ResourceStatus::Deleting,
1082            ];
1083            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
1084            assert_eq!(result, StackStatus::Failure);
1085        }
1086
1087        #[test]
1088        fn test_compute_stack_status_mixed_success_and_in_progress() {
1089            let statuses = vec![
1090                ResourceStatus::Running,
1091                ResourceStatus::Provisioning,
1092                ResourceStatus::Running,
1093            ];
1094            let result = StackState::compute_stack_status_from_resources(&statuses).unwrap();
1095            assert_eq!(result, StackStatus::InProgress);
1096        }
1097
1098        #[test]
1099        fn test_stack_state_status_computation() {
1100            let mut stack_state = StackState::new(Platform::Aws);
1101
1102            // Initially should be pending (no resources)
1103            assert_eq!(
1104                stack_state.compute_stack_status().unwrap(),
1105                StackStatus::Pending
1106            );
1107
1108            // Add a running resource
1109            let test_worker = Worker::new("test-worker".to_string())
1110                .code(WorkerCode::Image {
1111                    image: "test:latest".to_string(),
1112                })
1113                .permissions("test-profile".to_string())
1114                .build();
1115
1116            let resource_state = StackResourceState::new_pending(
1117                "worker".to_string(),
1118                Resource::new(test_worker),
1119                None,
1120                Vec::new(),
1121            )
1122            .with_updates(|state| {
1123                state.status = ResourceStatus::Running;
1124            });
1125
1126            stack_state
1127                .resources
1128                .insert("test-worker".to_string(), resource_state);
1129
1130            // Compute status
1131            assert_eq!(
1132                stack_state.compute_stack_status().unwrap(),
1133                StackStatus::Running
1134            );
1135        }
1136
1137        /// Regression test: externally provisioned AzureContainerAppsEnvironment
1138        /// must survive a JSON serialization roundtrip (simulates push model's
1139        /// state transfer through the manager API and SQLite).
1140        #[test]
1141        fn test_external_container_env_survives_json_roundtrip() {
1142            use crate::resources::AzureContainerAppsEnvironmentOutputs;
1143            use crate::AzureContainerAppsEnvironment;
1144
1145            let mut stack_state = StackState::new(Platform::Azure);
1146
1147            // 1. Create the container env resource
1148            //    (mirrors what executor.step() does for external bindings)
1149            let env_config =
1150                AzureContainerAppsEnvironment::new("default-container-env".to_string()).build();
1151            let env_outputs = AzureContainerAppsEnvironmentOutputs {
1152                environment_name: "test-env".to_string(),
1153                resource_id: "/subscriptions/sub-id/resourceGroups/rg/providers/Microsoft.App/managedEnvironments/test-env".to_string(),
1154                resource_group_name: "shared-rg".to_string(),
1155                default_domain: "test-env.azurecontainerapps.io".to_string(),
1156                static_ip: Some("10.0.0.1".to_string()),
1157                custom_domain_verification_id: None,
1158            };
1159
1160            let env_state = StackResourceState::new_pending(
1161                AzureContainerAppsEnvironment::RESOURCE_TYPE.to_string(),
1162                Resource::new(env_config),
1163                Some(ResourceLifecycle::Frozen),
1164                Vec::new(),
1165            )
1166            .with_updates(|state| {
1167                state.status = ResourceStatus::Running;
1168                state.outputs = Some(ResourceOutputs::new(env_outputs.clone()));
1169            });
1170
1171            stack_state
1172                .resources
1173                .insert("default-container-env".to_string(), env_state);
1174
1175            // 2. Also add a worker that depends on it (like the real stack)
1176            let test_worker = Worker::new("alien-rs-worker".to_string())
1177                .code(WorkerCode::Image {
1178                    image: "test:latest".to_string(),
1179                })
1180                .permissions("execution".to_string())
1181                .build();
1182
1183            let fn_state = StackResourceState::new_pending(
1184                "worker".to_string(),
1185                Resource::new(test_worker),
1186                Some(ResourceLifecycle::Live),
1187                vec![crate::ResourceRef::new(
1188                    AzureContainerAppsEnvironment::RESOURCE_TYPE,
1189                    "default-container-env",
1190                )],
1191            )
1192            .with_updates(|state| {
1193                state.status = ResourceStatus::Running;
1194            });
1195
1196            stack_state
1197                .resources
1198                .insert("alien-rs-worker".to_string(), fn_state);
1199
1200            // 3. Verify before roundtrip
1201            assert!(
1202                stack_state.resources.contains_key("default-container-env"),
1203                "default-container-env should be in state before roundtrip"
1204            );
1205            assert_eq!(stack_state.resources.len(), 2);
1206
1207            // 4. Simulate the push model roundtrip:
1208            //    push client: serde_json::to_value(state) → send to manager API
1209            //    manager API: serde_json::from_value(json) → DeploymentState
1210            //    manager store: serde_json::to_string(stack_state) → SQLite TEXT
1211            //    manager read: serde_json::from_str(text) → StackState
1212
1213            // Step A: to_value (what ManagerApiTransport.reconcile_step does)
1214            let json_value = serde_json::to_value(&stack_state)
1215                .expect("StackState serialization to Value should not fail");
1216
1217            // Step B: from_value (what the manager reconcile handler does)
1218            let deserialized_from_value: StackState = serde_json::from_value(json_value)
1219                .expect("StackState deserialization from Value should not fail");
1220
1221            assert!(
1222                deserialized_from_value
1223                    .resources
1224                    .contains_key("default-container-env"),
1225                "default-container-env lost during to_value/from_value roundtrip! \
1226                 Available: {:?}",
1227                deserialized_from_value.resources.keys().collect::<Vec<_>>()
1228            );
1229
1230            // Step C: to_string (what SQLite store does)
1231            let json_string = serde_json::to_string(&deserialized_from_value)
1232                .expect("StackState serialization to String should not fail");
1233
1234            // Step D: from_str (what SQLite store does on read)
1235            let deserialized_from_str: StackState = serde_json::from_str(&json_string)
1236                .expect("StackState deserialization from String should not fail");
1237
1238            assert!(
1239                deserialized_from_str
1240                    .resources
1241                    .contains_key("default-container-env"),
1242                "default-container-env lost during to_string/from_str roundtrip! \
1243                 Available: {:?}",
1244                deserialized_from_str.resources.keys().collect::<Vec<_>>()
1245            );
1246
1247            // 5. Verify the outputs survived too
1248            let outputs = deserialized_from_str
1249                .get_resource_outputs::<AzureContainerAppsEnvironmentOutputs>(
1250                    "default-container-env",
1251                )
1252                .expect("Should be able to get container env outputs after roundtrip");
1253            assert_eq!(outputs.environment_name, "test-env");
1254            assert_eq!(outputs.resource_group_name, "shared-rg");
1255            assert_eq!(outputs.static_ip, Some("10.0.0.1".to_string()));
1256
1257            // 6. Verify status and lifecycle survived
1258            let env_resource = deserialized_from_str
1259                .resources
1260                .get("default-container-env")
1261                .unwrap();
1262            assert_eq!(env_resource.status, ResourceStatus::Running);
1263            assert_eq!(env_resource.lifecycle, Some(ResourceLifecycle::Frozen));
1264        }
1265
1266        /// Test the full DeploymentState roundtrip (not just StackState),
1267        /// since the push model serializes the entire DeploymentState.
1268        #[test]
1269        fn test_deployment_state_roundtrip_preserves_external_binding() {
1270            use crate::resources::AzureContainerAppsEnvironmentOutputs;
1271            use crate::{AzureContainerAppsEnvironment, DeploymentState, DeploymentStatus};
1272
1273            let mut stack_state = StackState::new(Platform::Azure);
1274
1275            let env_config =
1276                AzureContainerAppsEnvironment::new("default-container-env".to_string()).build();
1277            let env_outputs = AzureContainerAppsEnvironmentOutputs {
1278                environment_name: "test-env".to_string(),
1279                resource_id: "/subscriptions/sub/rg/env".to_string(),
1280                resource_group_name: "shared-rg".to_string(),
1281                default_domain: "test.io".to_string(),
1282                static_ip: None,
1283                custom_domain_verification_id: None,
1284            };
1285
1286            let env_state = StackResourceState::new_pending(
1287                AzureContainerAppsEnvironment::RESOURCE_TYPE.to_string(),
1288                Resource::new(env_config),
1289                Some(ResourceLifecycle::Frozen),
1290                Vec::new(),
1291            )
1292            .with_updates(|state| {
1293                state.status = ResourceStatus::Running;
1294                state.outputs = Some(ResourceOutputs::new(env_outputs));
1295            });
1296
1297            stack_state
1298                .resources
1299                .insert("default-container-env".to_string(), env_state);
1300
1301            // Build DeploymentState (what final_reconcile serializes)
1302            let deployment_state = DeploymentState {
1303                status: DeploymentStatus::Provisioning,
1304                platform: Platform::Azure,
1305                current_release: None,
1306                target_release: None,
1307                stack_state: Some(stack_state),
1308                error: None,
1309                environment_info: None,
1310                runtime_metadata: None,
1311                retry_requested: false,
1312                protocol_version: 1,
1313            };
1314
1315            // Roundtrip through serde_json::Value (what the push client does)
1316            let json_value =
1317                serde_json::to_value(&deployment_state).expect("DeploymentState to_value failed");
1318
1319            let deserialized: DeploymentState =
1320                serde_json::from_value(json_value).expect("DeploymentState from_value failed");
1321
1322            let ss = deserialized
1323                .stack_state
1324                .as_ref()
1325                .expect("stack_state should be present");
1326
1327            assert!(
1328                ss.resources.contains_key("default-container-env"),
1329                "default-container-env lost in DeploymentState roundtrip! \
1330                 Available: {:?}",
1331                ss.resources.keys().collect::<Vec<_>>()
1332            );
1333        }
1334    }
1335}