-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmod.rs
More file actions
1899 lines (1710 loc) · 69.6 KB
/
Copy pathmod.rs
File metadata and controls
1899 lines (1710 loc) · 69.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Environment State Marker Types
//!
//! This module defines the state marker types used in the type-state pattern
//! for the Environment entity. Each state represents a distinct phase in the
//! deployment lifecycle and is enforced at compile-time.
//!
//! ## Type-State Pattern
//!
//! The type-state pattern uses Rust's type system to enforce state machine
//! transitions at compile-time. Each state is a distinct type, and the
//! `Environment<S>` struct is generic over the state type. This ensures that
//! invalid state transitions are caught during compilation rather than at runtime.
//!
//! ## State Lifecycle
//!
//! ### Happy Path
//!
//! ```text
//! Created → Provisioning → Provisioned → Configuring → Configured
//! → Releasing → Released → Running → Destroyed
//! ```
//!
//! ### Error States
//!
//! At each operational phase, the system can transition to a corresponding
//! failed state if an error occurs:
//!
//! - `Provisioning` → `ProvisionFailed`
//! - `Configuring` → `ConfigureFailed`
//! - `Releasing` → `ReleaseFailed`
//! - `Running` → `RunFailed`
//!
//! ## Usage Example
//!
//! ```rust
//! use torrust_tracker_deployer_lib::domain::environment::state::{Created, Provisioning};
//!
//! // State types are used as type parameters for Environment<S>
//! // let env: Environment<Created> = Environment::new(name, credentials);
//! // let env: Environment<Provisioning> = env.start_provisioning();
//! ```
use serde::{Deserialize, Serialize};
use thiserror::Error;
// State modules
mod common;
mod configure_failed;
mod configured;
mod configuring;
mod created;
mod destroy_failed;
mod destroyed;
mod destroying;
mod provision_failed;
mod provisioned;
mod provisioning;
mod release_failed;
mod released;
mod releasing;
mod run_failed;
mod running;
// Re-export state types
pub use common::BaseFailureContext;
pub use configure_failed::{ConfigureFailed, ConfigureFailureContext, ConfigureStep};
pub use configured::Configured;
pub use configuring::Configuring;
pub use created::Created;
pub use destroy_failed::{DestroyFailed, DestroyFailureContext, DestroyStep};
pub use destroyed::Destroyed;
pub use destroying::Destroying;
pub use provision_failed::{ProvisionFailed, ProvisionFailureContext, ProvisionStep};
pub use provisioned::Provisioned;
pub use provisioning::Provisioning;
pub use release_failed::ReleaseFailed;
pub use released::Released;
pub use releasing::Releasing;
pub use run_failed::RunFailed;
pub use running::Running;
/// Error type for invalid type conversions when working with type-erased environments
///
/// This error occurs when attempting to convert an `AnyEnvironmentState` to a specific
/// typed `Environment<S>` state, but the runtime state doesn't match the expected type.
///
/// # Example
///
/// ```rust
/// use torrust_tracker_deployer_lib::domain::environment::state::AnyEnvironmentState;
///
/// // let any_env = AnyEnvironmentState::Provisioned(...);
/// // // This will fail because any_env is Provisioned, not Created
/// // let result = any_env.try_into_created();
/// // assert!(result.is_err());
/// ```
#[derive(Debug, Clone, Error)]
pub enum StateTypeError {
/// The environment is in a different state than expected
#[error("Expected state '{expected}', but found '{actual}'")]
UnexpectedState {
/// The state type that was expected
expected: &'static str,
/// The actual state type that was found
actual: String,
},
}
// Import Environment for type erasure enum
use crate::domain::environment::{Environment, EnvironmentName};
/// Type-erased environment that can hold any typed `Environment<S>` at runtime
///
/// This enum enables runtime handling of `Environment<S>` instances without
/// knowing their specific state type at compile time. This is essential for:
///
/// - **Serialization**: Saving environments to disk (JSON files)
/// - **Deserialization**: Loading environments from disk
/// - **Collections**: Storing environments with different states together
/// - **Runtime Inspection**: Checking state without compile-time type knowledge
/// - **Generic Interfaces**: Passing through non-generic function parameters
///
/// ## Type Erasure Pattern
///
/// Each variant wraps a typed `Environment<S>` where `S` is one of the state
/// marker types defined in this module. The enum variant name acts as a
/// discriminator (similar to a `type` column in database Single Table Inheritance).
///
/// ## Usage Example
///
/// ```rust
/// use torrust_tracker_deployer_lib::domain::environment::state::AnyEnvironmentState;
///
/// // Type erasure: typed -> runtime
/// // let env: Environment<Provisioned> = ...;
/// // let any_env: AnyEnvironmentState = env.into_any();
///
/// // Serialization
/// // let json = serde_json::to_string(&any_env)?;
///
/// // Deserialization
/// // let any_env: AnyEnvironmentState = serde_json::from_str(&json)?;
///
/// // Type restoration: runtime -> typed
/// // let env: Environment<Provisioned> = any_env.try_into_provisioned()?;
/// ```
///
/// ## Design Decision
///
/// See [ADR: Type Erasure for Environment States](../../docs/decisions/type-erasure-for-environment-states.md)
/// for detailed rationale behind this design choice.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AnyEnvironmentState {
/// Environment in `Created` state
Created(Environment<Created>),
/// Environment in `Provisioning` state
Provisioning(Environment<Provisioning>),
/// Environment in `Provisioned` state
Provisioned(Environment<Provisioned>),
/// Environment in `Configuring` state
Configuring(Environment<Configuring>),
/// Environment in `Configured` state
Configured(Environment<Configured>),
/// Environment in `Releasing` state
Releasing(Environment<Releasing>),
/// Environment in `Released` state
Released(Environment<Released>),
/// Environment in `Running` state
Running(Environment<Running>),
/// Environment in `Destroying` state
Destroying(Environment<Destroying>),
/// Environment in `ProvisionFailed` error state
ProvisionFailed(Environment<ProvisionFailed>),
/// Environment in `ConfigureFailed` error state
ConfigureFailed(Environment<ConfigureFailed>),
/// Environment in `ReleaseFailed` error state
ReleaseFailed(Environment<ReleaseFailed>),
/// Environment in `RunFailed` error state
RunFailed(Environment<RunFailed>),
/// Environment in `DestroyFailed` error state
DestroyFailed(Environment<DestroyFailed>),
/// Environment in `Destroyed` terminal state
Destroyed(Environment<Destroyed>),
}
// Introspection methods for AnyEnvironmentState
impl AnyEnvironmentState {
/// Get a reference to the environment context regardless of current state
///
/// This helper method centralizes state matching for accessing
/// state-independent data. Instead of pattern matching 6 times
/// (once per field accessor), we match once and reuse the result.
///
/// This is a private implementation detail that simplifies the
/// public accessor methods.
///
/// # Returns
///
/// A reference to the `EnvironmentContext` contained within the environment.
fn context(&self) -> &crate::domain::environment::EnvironmentContext {
match self {
Self::Created(env) => env.context(),
Self::Provisioning(env) => env.context(),
Self::Provisioned(env) => env.context(),
Self::Configuring(env) => env.context(),
Self::Configured(env) => env.context(),
Self::Releasing(env) => env.context(),
Self::Released(env) => env.context(),
Self::Running(env) => env.context(),
Self::Destroying(env) => env.context(),
Self::ProvisionFailed(env) => env.context(),
Self::ConfigureFailed(env) => env.context(),
Self::ReleaseFailed(env) => env.context(),
Self::RunFailed(env) => env.context(),
Self::DestroyFailed(env) => env.context(),
Self::Destroyed(env) => env.context(),
}
}
/// Get the environment name regardless of current state
///
/// This method provides access to the environment name without needing to
/// pattern match on the specific state variant.
///
/// # Returns
///
/// A reference to the `EnvironmentName` contained within the environment.
#[must_use]
pub fn name(&self) -> &EnvironmentName {
&self.context().user_inputs.name
}
/// Get the state name as a string
///
/// Returns a static string identifier for the current state. This is useful
/// for logging, error messages, and displaying state information to users.
///
/// # Returns
///
/// A static string representing the state name (e.g., "created", "provisioning").
#[must_use]
pub fn state_name(&self) -> &'static str {
match self {
Self::Created(_) => "created",
Self::Provisioning(_) => "provisioning",
Self::Provisioned(_) => "provisioned",
Self::Configuring(_) => "configuring",
Self::Configured(_) => "configured",
Self::Releasing(_) => "releasing",
Self::Released(_) => "released",
Self::Running(_) => "running",
Self::Destroying(_) => "destroying",
Self::ProvisionFailed(_) => "provision_failed",
Self::ConfigureFailed(_) => "configure_failed",
Self::ReleaseFailed(_) => "release_failed",
Self::RunFailed(_) => "run_failed",
Self::DestroyFailed(_) => "destroy_failed",
Self::Destroyed(_) => "destroyed",
}
}
/// Check if the environment is in a success (non-error) state
///
/// Success states are those representing normal operation flow, including
/// transient states (like `Provisioning`) and terminal success states
/// (like `Running`, `Destroyed`).
///
/// # Returns
///
/// `true` if the environment is in a success state, `false` for error states.
#[must_use]
pub fn is_success_state(&self) -> bool {
matches!(
self,
Self::Created(_)
| Self::Provisioning(_)
| Self::Provisioned(_)
| Self::Configuring(_)
| Self::Configured(_)
| Self::Releasing(_)
| Self::Released(_)
| Self::Running(_)
| Self::Destroying(_)
| Self::Destroyed(_)
)
}
/// Check if the environment is in an error state
///
/// Error states indicate that an operation failed during the environment's
/// lifecycle (provisioning, configuration, release, or runtime).
///
/// # Returns
///
/// `true` if the environment is in an error state, `false` otherwise.
#[must_use]
pub fn is_error_state(&self) -> bool {
matches!(
self,
Self::ProvisionFailed(_)
| Self::ConfigureFailed(_)
| Self::ReleaseFailed(_)
| Self::RunFailed(_)
| Self::DestroyFailed(_)
)
}
/// Check if the environment is in a terminal state
///
/// Terminal states are final states where no more transitions are expected.
/// This includes both successful terminal states (`Running`, `Destroyed`)
/// and error states (all `*Failed` variants).
///
/// # Returns
///
/// `true` if the environment is in a terminal state, `false` otherwise.
#[must_use]
pub fn is_terminal_state(&self) -> bool {
matches!(
self,
Self::Running(_)
| Self::Destroyed(_)
| Self::ProvisionFailed(_)
| Self::ConfigureFailed(_)
| Self::ReleaseFailed(_)
| Self::RunFailed(_)
| Self::DestroyFailed(_)
)
}
/// Get error details if the environment is in an error state
///
/// For error states (`*Failed`), this returns the description of the
/// operation that failed. For non-error states, returns `None`.
///
/// # Returns
///
/// - `Some(&str)` containing the failed operation description for error states
/// - `None` for success states
#[must_use]
pub fn error_details(&self) -> Option<&str> {
match self {
Self::ProvisionFailed(env) => Some(&env.state().context.base.error_summary),
Self::ConfigureFailed(env) => Some(&env.state().context.base.error_summary),
Self::ReleaseFailed(env) => Some(&env.state().failed_step),
Self::RunFailed(env) => Some(&env.state().failed_step),
Self::DestroyFailed(env) => Some(&env.state().context.base.error_summary),
_ => None,
}
}
/// Get the instance name regardless of current state
///
/// This method provides access to the instance name without needing to
/// pattern match on the specific state variant.
///
/// # Returns
///
/// A reference to the `InstanceName` contained within the environment.
#[must_use]
pub fn instance_name(&self) -> &crate::domain::environment::InstanceName {
&self.context().user_inputs.instance_name
}
/// Get the profile name regardless of current state
///
/// This method provides access to the profile name without needing to
/// pattern match on the specific state variant.
///
/// # Returns
///
/// A reference to the `ProfileName` contained within the environment.
#[must_use]
pub fn profile_name(&self) -> &crate::domain::environment::ProfileName {
&self.context().user_inputs.profile_name
}
/// Get the SSH credentials regardless of current state
///
/// This method provides access to the SSH credentials without needing to
/// pattern match on the specific state variant.
///
/// # Returns
///
/// A reference to the `SshCredentials` contained within the environment.
#[must_use]
pub fn ssh_credentials(&self) -> &crate::adapters::ssh::SshCredentials {
&self.context().user_inputs.ssh_credentials
}
/// Get the SSH port regardless of current state
///
/// This method provides access to the SSH port without needing to
/// pattern match on the specific state variant.
///
/// # Returns
///
/// The SSH port number.
#[must_use]
pub fn ssh_port(&self) -> u16 {
self.context().user_inputs.ssh_port
}
/// Get the instance IP address if available, regardless of current state
///
/// This method provides access to the instance IP without needing to
/// pattern match on the specific state variant.
///
/// # Returns
///
/// - `Some(IpAddr)` if the environment has been provisioned
/// - `None` if the environment hasn't been provisioned yet
#[must_use]
pub fn instance_ip(&self) -> Option<std::net::IpAddr> {
self.context().runtime_outputs.instance_ip
}
/// Destroy the environment, transitioning it to the Destroyed state
///
/// This method provides a unified interface to destroy an environment
/// regardless of its current state. It encapsulates the repetitive match
/// pattern that would otherwise be needed in calling code.
///
/// # Returns
///
/// - `Ok(Environment<Destroyed>)` if the environment was successfully destroyed
/// - `Err(StateTypeError)` if the environment is already in the `Destroyed` state
///
/// # Errors
///
/// Returns `StateTypeError::UnexpectedState` if called on an environment
/// already in the `Destroyed` state.
pub fn destroy(self) -> Result<Environment<Destroyed>, StateTypeError> {
match self {
Self::Created(env) => Ok(env.destroy()),
Self::Provisioning(env) => Ok(env.destroy()),
Self::Provisioned(env) => Ok(env.destroy()),
Self::Configuring(env) => Ok(env.destroy()),
Self::Configured(env) => Ok(env.destroy()),
Self::Releasing(env) => Ok(env.destroy()),
Self::Released(env) => Ok(env.destroy()),
Self::Running(env) => Ok(env.destroy()),
Self::Destroying(env) => Ok(env.destroy()),
Self::ProvisionFailed(env) => Ok(env.destroy()),
Self::ConfigureFailed(env) => Ok(env.destroy()),
Self::ReleaseFailed(env) => Ok(env.destroy()),
Self::RunFailed(env) => Ok(env.destroy()),
Self::DestroyFailed(env) => Ok(env.destroy()),
Self::Destroyed(_) => Err(StateTypeError::UnexpectedState {
expected: "any state except destroyed",
actual: "destroyed".to_string(),
}),
}
}
/// Get the `OpenTofu` build directory path regardless of current state
///
/// This method provides a unified interface to access the build directory
/// for `OpenTofu` operations without needing to pattern match on the
/// specific state variant.
///
/// The path is returned consistently regardless of the environment's state.
/// The caller is responsible for determining how to use the path based on
/// their specific needs and the environment's current state.
///
/// # Returns
///
/// The path to the `OpenTofu` build directory for the LXD provider.
#[must_use]
pub fn tofu_build_dir(&self) -> std::path::PathBuf {
self.context().tofu_build_dir()
}
}
/// Display implementation for user-friendly state representation
///
/// Formats the environment state in a human-readable way, including the
/// environment name, current state, and error details if applicable.
///
/// # Examples
///
/// ```text
/// Environment 'my-env' is in state: provisioning
/// Environment 'my-env' is in state: provision_failed (failed at: network timeout)
/// ```
impl std::fmt::Display for AnyEnvironmentState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Environment '{}' is in state: {}",
self.name().as_str(),
self.state_name()
)?;
if let Some(error_details) = self.error_details() {
write!(f, " (failed at: {error_details})")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::adapters::ssh::SshCredentials;
use crate::domain::environment::name::EnvironmentName;
use crate::shared::Username;
use std::path::PathBuf;
/// Helper to create test SSH credentials
fn create_test_ssh_credentials() -> SshCredentials {
let username = Username::new("test-user".to_string()).unwrap();
SshCredentials::new(
PathBuf::from("/tmp/test_key"),
PathBuf::from("/tmp/test_key.pub"),
username,
)
}
/// Helper to create a test environment in Created state
fn create_test_environment_created() -> Environment<Created> {
let name = EnvironmentName::new("test-env".to_string()).unwrap();
let ssh_creds = create_test_ssh_credentials();
Environment::new(name, ssh_creds, 22)
}
/// Helper to create a test `ProvisionFailureContext` with custom error message
fn create_test_provision_context(error_message: &str) -> ProvisionFailureContext {
use crate::domain::environment::TraceId;
use crate::shared::ErrorKind;
use chrono::Utc;
use std::time::Duration;
ProvisionFailureContext {
failed_step: ProvisionStep::OpenTofuApply,
error_kind: ErrorKind::InfrastructureOperation,
base: BaseFailureContext {
error_summary: error_message.to_string(),
failed_at: Utc::now(),
execution_started_at: Utc::now(),
execution_duration: Duration::from_secs(0),
trace_id: TraceId::default(),
trace_file_path: None,
},
}
}
/// Helper to create a test `ConfigureFailureContext` with custom error message
fn create_test_configure_context(error_message: &str) -> ConfigureFailureContext {
use crate::domain::environment::TraceId;
use crate::shared::ErrorKind;
use chrono::Utc;
use std::time::Duration;
ConfigureFailureContext {
failed_step: ConfigureStep::InstallDocker,
error_kind: ErrorKind::CommandExecution,
base: BaseFailureContext {
error_summary: error_message.to_string(),
failed_at: Utc::now(),
execution_started_at: Utc::now(),
execution_duration: Duration::from_secs(0),
trace_id: TraceId::default(),
trace_file_path: None,
},
}
}
/// Test module for state marker types
///
/// These tests verify that state types can be created, cloned, and serialized
/// correctly. They ensure basic functionality of the state marker types.
#[test]
fn it_should_create_provisioning_state() {
let state = Provisioning;
assert_eq!(state, Provisioning);
}
#[test]
fn it_should_create_provisioned_state() {
let state = Provisioned;
assert_eq!(state, Provisioned);
}
#[test]
fn it_should_create_configuring_state() {
let state = Configuring;
assert_eq!(state, Configuring);
}
#[test]
fn it_should_create_configured_state() {
let state = Configured;
assert_eq!(state, Configured);
}
#[test]
fn it_should_create_releasing_state() {
let state = Releasing;
assert_eq!(state, Releasing);
}
#[test]
fn it_should_create_released_state() {
let state = Released;
assert_eq!(state, Released);
}
#[test]
fn it_should_create_running_state() {
let state = Running;
assert_eq!(state, Running);
}
#[test]
fn it_should_create_provision_failed_state_with_context() {
let state = ProvisionFailed {
context: create_test_provision_context("cloud_init_execution"),
};
assert_eq!(state.context.base.error_summary, "cloud_init_execution");
}
#[test]
fn it_should_clone_provision_failed_state() {
let state = ProvisionFailed {
context: create_test_provision_context("cloud_init_execution"),
};
let cloned = state.clone();
assert_eq!(state, cloned);
}
#[test]
fn it_should_create_configure_failed_state_with_context() {
let state = ConfigureFailed {
context: create_test_configure_context("ansible_playbook_execution"),
};
assert_eq!(
state.context.base.error_summary,
"ansible_playbook_execution"
);
}
#[test]
fn it_should_create_release_failed_state_with_context() {
let state = ReleaseFailed {
failed_step: "build_artifacts".to_string(),
};
assert_eq!(state.failed_step, "build_artifacts");
}
#[test]
fn it_should_create_run_failed_state_with_context() {
let state = RunFailed {
failed_step: "application_startup".to_string(),
};
assert_eq!(state.failed_step, "application_startup");
}
#[test]
fn it_should_create_destroyed_state() {
let state = Destroyed;
assert_eq!(state, Destroyed);
}
#[test]
fn it_should_serialize_provision_failed_state_to_json() {
let state = ProvisionFailed {
context: create_test_provision_context("cloud_init"),
};
let json = serde_json::to_string(&state).unwrap();
assert!(json.contains("cloud_init"));
assert!(json.contains("context"));
}
#[test]
fn it_should_deserialize_provision_failed_state_from_json() {
// Note: This test now uses the full context structure
let context = create_test_provision_context("cloud_init");
let state = ProvisionFailed {
context: context.clone(),
};
let json = serde_json::to_string(&state).unwrap();
let deserialized: ProvisionFailed = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.context.base.error_summary, "cloud_init");
}
#[test]
fn it_should_serialize_configure_failed_state_to_json() {
let state = ConfigureFailed {
context: create_test_configure_context("ansible_playbook"),
};
let json = serde_json::to_string(&state).unwrap();
assert!(json.contains("InstallDocker"));
assert!(json.contains("CommandExecution"));
let deserialized: ConfigureFailed = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.context.base.error_summary, "ansible_playbook");
}
#[test]
fn it_should_deserialize_configure_failed_state_from_json() {
// Note: This test now uses the full context structure
let context = create_test_configure_context("ansible_playbook");
let state = ConfigureFailed {
context: context.clone(),
};
let json = serde_json::to_string(&state).unwrap();
let deserialized: ConfigureFailed = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.context.base.error_summary, "ansible_playbook");
}
// Tests for AnyEnvironmentState enum (Type Erasure)
mod any_environment_state_tests {
use super::*;
// Note: Helper functions for creating test environments and contexts
// are defined in the parent module and can be accessed via super::
#[test]
fn it_should_create_any_environment_state_with_created_variant() {
let env = super::create_test_environment_created();
let any_env = AnyEnvironmentState::Created(env);
assert!(matches!(any_env, AnyEnvironmentState::Created(_)));
}
// Note: Tests for other state variants will be added in Subtask 2
// once we have the conversion methods (into_any()) that properly
// create environments in different states through state transitions.
#[test]
fn it_should_clone_any_environment_state() {
let env = super::create_test_environment_created();
let any_env = AnyEnvironmentState::Created(env);
let cloned = any_env.clone();
assert!(matches!(cloned, AnyEnvironmentState::Created(_)));
}
#[test]
fn it_should_debug_format_any_environment_state() {
let env = super::create_test_environment_created();
let any_env = AnyEnvironmentState::Created(env);
let debug_str = format!("{any_env:?}");
assert!(debug_str.contains("Created"));
}
#[test]
fn it_should_serialize_any_environment_state_to_json() {
let env = super::create_test_environment_created();
let any_env = AnyEnvironmentState::Created(env);
let json = serde_json::to_string(&any_env).unwrap();
assert!(json.contains("Created"));
}
// Tests for Type Conversion Methods (Subtask 2)
// Tests for into_any() - Typed to Runtime conversions
#[test]
fn it_should_convert_provisioning_environment_into_any() {
let env = super::create_test_environment_created().start_provisioning();
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::Provisioning(_)));
}
#[test]
fn it_should_convert_provisioned_environment_into_any() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned();
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::Provisioned(_)));
}
#[test]
fn it_should_convert_configuring_environment_into_any() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring();
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::Configuring(_)));
}
#[test]
fn it_should_convert_configured_environment_into_any() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configured();
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::Configured(_)));
}
#[test]
fn it_should_convert_releasing_environment_into_any() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configured()
.start_releasing();
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::Releasing(_)));
}
#[test]
fn it_should_convert_released_environment_into_any() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configured()
.start_releasing()
.released();
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::Released(_)));
}
#[test]
fn it_should_convert_running_environment_into_any() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configured()
.start_releasing()
.released()
.start_running();
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::Running(_)));
}
#[test]
fn it_should_convert_provision_failed_environment_into_any() {
let env = super::create_test_environment_created()
.start_provisioning()
.provision_failed(super::create_test_provision_context("infrastructure error"));
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::ProvisionFailed(_)));
}
#[test]
fn it_should_convert_configure_failed_environment_into_any() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configure_failed(super::create_test_configure_context("ansible error"));
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::ConfigureFailed(_)));
}
#[test]
fn it_should_convert_release_failed_environment_into_any() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configured()
.start_releasing()
.release_failed("release error".to_string());
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::ReleaseFailed(_)));
}
#[test]
fn it_should_convert_run_failed_environment_into_any() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configured()
.start_releasing()
.released()
.start_running()
.run_failed("runtime error".to_string());
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::RunFailed(_)));
}
#[test]
fn it_should_convert_destroyed_environment_into_any() {
let env = super::create_test_environment_created().destroy();
let any_env = env.into_any();
assert!(matches!(any_env, AnyEnvironmentState::Destroyed(_)));
}
// Tests for try_into_<state>() - Runtime to Typed conversions (successful cases)
#[test]
fn it_should_convert_any_to_provisioning_successfully() {
let env = super::create_test_environment_created().start_provisioning();
let any_env = env.into_any();
let result = any_env.try_into_provisioning();
assert!(result.is_ok());
}
#[test]
fn it_should_convert_any_to_provisioned_successfully() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned();
let any_env = env.into_any();
let result = any_env.try_into_provisioned();
assert!(result.is_ok());
}
#[test]
fn it_should_convert_any_to_configuring_successfully() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring();
let any_env = env.into_any();
let result = any_env.try_into_configuring();
assert!(result.is_ok());
}
#[test]
fn it_should_convert_any_to_configured_successfully() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configured();
let any_env = env.into_any();
let result = any_env.try_into_configured();
assert!(result.is_ok());
}
#[test]
fn it_should_convert_any_to_releasing_successfully() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configured()
.start_releasing();
let any_env = env.into_any();
let result = any_env.try_into_releasing();
assert!(result.is_ok());
}
#[test]
fn it_should_convert_any_to_released_successfully() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configured()
.start_releasing()
.released();
let any_env = env.into_any();
let result = any_env.try_into_released();
assert!(result.is_ok());
}
#[test]
fn it_should_convert_any_to_running_successfully() {
let env = super::create_test_environment_created()
.start_provisioning()
.provisioned()
.start_configuring()
.configured()
.start_releasing()
.released()
.start_running();
let any_env = env.into_any();
let result = any_env.try_into_running();
assert!(result.is_ok());
}
#[test]
fn it_should_convert_any_to_provision_failed_successfully() {
let env = super::create_test_environment_created()
.start_provisioning()
.provision_failed(super::create_test_provision_context("test error"));
let any_env = env.into_any();
let result = any_env.try_into_provision_failed();
assert!(result.is_ok());
}
#[test]
fn it_should_convert_any_to_configure_failed_successfully() {