1use 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#[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 Pending,
62 InProgress,
64 Running,
66 Deleted,
68 Failure,
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
74#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
75#[serde(rename_all = "camelCase")]
76pub struct StackState {
77 pub platform: Platform,
79 pub resources: HashMap<String, StackResourceState>,
81 pub resource_prefix: String,
83}
84
85impl StackState {
86 pub fn new(platform: Platform) -> Self {
88 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 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 pub fn resource(&self, id: &str) -> Option<&StackResourceState> {
117 self.resources.get(id)
118 }
119
120 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 pub fn compute_stack_status_from_resources(
135 resource_statuses: &[ResourceStatus],
136 ) -> Result<StackStatus> {
137 if resource_statuses.is_empty() {
139 return Ok(StackStatus::Pending);
140 }
141
142 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 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 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 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 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 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#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
265#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
266#[serde(rename_all = "camelCase")]
267pub struct StackResourceState {
268 #[serde(rename = "type")]
270 pub resource_type: String,
271
272 #[serde(rename = "_internal", skip_serializing_if = "Option::is_none")]
276 pub internal_state: Option<serde_json::Value>,
277
278 pub status: ResourceStatus,
280
281 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
289 pub progress: Option<String>,
290
291 #[serde(skip_serializing_if = "Option::is_none")]
293 pub outputs: Option<ResourceOutputs>,
294
295 pub config: Resource,
297
298 #[serde(skip_serializing_if = "Option::is_none")]
301 pub previous_config: Option<Resource>,
302
303 #[serde(default, skip_serializing_if = "is_zero")]
305 #[builder(default)]
306 pub retry_attempt: u32,
307
308 #[serde(skip_serializing_if = "Option::is_none")]
310 pub error: Option<AlienError>,
311
312 #[serde(skip_serializing_if = "Option::is_none")]
315 pub lifecycle: Option<ResourceLifecycle>,
316
317 #[serde(default, skip_serializing_if = "Option::is_none")]
320 pub controller_platform: Option<Platform>,
321
322 #[serde(default, skip_serializing_if = "Vec::is_empty")]
325 #[builder(default = vec![])]
326 pub dependencies: Vec<ResourceRef>,
327
328 #[serde(skip_serializing_if = "Option::is_none")]
332 pub last_failed_state: Option<serde_json::Value>,
333
334 #[serde(skip_serializing_if = "Option::is_none")]
339 pub remote_binding_params: Option<serde_json::Value>,
340
341 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
346 #[builder(default)]
347 pub external_binding: bool,
348
349 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
354 #[builder(default)]
355 pub dependency_update_pending: bool,
356
357 #[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
371fn 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 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 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 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
437fn 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 #[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 #[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 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 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 let result = stack_state.get_resource_outputs::<WorkerOutputs>("nonexistent-worker");
602 assert!(result.is_err());
603 let error = result.unwrap_err();
604
605 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 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 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 let result = stack_state.get_resource_outputs::<WorkerOutputs>("test-worker");
652 assert!(result.is_err());
653 let error = result.unwrap_err();
654
655 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 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 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 let result = stack_state.get_resource_outputs::<WorkerOutputs>("test-storage");
696 assert!(result.is_err());
697 let error = result.unwrap_err();
698
699 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 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 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 #[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 #[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 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 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 assert_eq!(
1104 stack_state.compute_stack_status().unwrap(),
1105 StackStatus::Pending
1106 );
1107
1108 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 assert_eq!(
1132 stack_state.compute_stack_status().unwrap(),
1133 StackStatus::Running
1134 );
1135 }
1136
1137 #[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 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 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 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 let json_value = serde_json::to_value(&stack_state)
1215 .expect("StackState serialization to Value should not fail");
1216
1217 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 let json_string = serde_json::to_string(&deserialized_from_value)
1232 .expect("StackState serialization to String should not fail");
1233
1234 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 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 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]
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 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 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}