Skip to main content

ggen_core/lifecycle/
state_machine.rs

1//! Type-level lifecycle state machine for poka-yoke error prevention
2//!
3//! This module provides a type-level state machine that prevents invalid lifecycle
4//! phase transitions at compile time using PhantomData markers.
5//!
6//! # Poka-Yoke Design
7//!
8//! **Error Prevention**: Makes invalid phase transitions impossible at compile time.
9//! For example, you cannot call `deploy()` on a state that hasn't completed `build()`.
10//!
11//! # Example
12//!
13//! ```no_run
14//! use crate::lifecycle::state_machine::*;
15//!
16//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
17//! // Start with initial state
18//! let lifecycle = LifecycleStateMachine::<Initial>::new();
19//!
20//! // Valid transitions
21//! let lifecycle = lifecycle.init()?;
22//! let lifecycle = lifecycle.setup()?;
23//! let lifecycle = lifecycle.build()?;
24//! let lifecycle = lifecycle.test()?;
25//! let lifecycle = lifecycle.deploy()?;
26//!
27//! // Invalid transitions fail at compile time:
28//! // lifecycle.deploy() // Compile error: method doesn't exist on Built state
29//! # Ok(())
30//! # }
31//! ```
32
33use super::error::{LifecycleError, Result};
34use super::state::LifecycleState;
35use std::marker::PhantomData;
36
37/// Type-level markers for lifecycle states
38///
39/// These marker types encode the current state of the lifecycle in the type system,
40/// preventing invalid transitions at compile time.
41/// Initial state - lifecycle not started
42pub struct Initial;
43
44/// Initialized state - `init` phase completed
45pub struct Initialized;
46
47/// Setup state - `setup` phase completed
48pub struct Setup;
49
50/// Built state - `build` phase completed
51pub struct Built;
52
53/// Tested state - `test` phase completed
54pub struct Tested;
55
56/// Deployed state - `deploy` phase completed
57pub struct Deployed;
58
59/// Type-level lifecycle state machine
60///
61/// The `State` type parameter encodes the current lifecycle state, preventing
62/// invalid transitions at compile time.
63///
64/// **Poka-yoke**: Invalid state transitions are impossible - the compiler prevents them.
65#[derive(Debug, Clone)]
66pub struct LifecycleStateMachine<State> {
67    /// Current lifecycle state
68    pub(crate) state: LifecycleState,
69    /// Type-level state marker (compile-time only, zero runtime cost)
70    pub(crate) _marker: PhantomData<State>,
71}
72
73impl LifecycleStateMachine<Initial> {
74    /// Create a new lifecycle state machine in the initial state
75    pub fn new() -> Self {
76        Self {
77            state: LifecycleState::default(),
78            _marker: PhantomData,
79        }
80    }
81
82    /// Transition from Initial to Initialized (run `init` phase)
83    ///
84    /// **Poka-yoke**: Can only be called on `Initial` state - compiler enforces this.
85    pub fn init(self) -> Result<LifecycleStateMachine<Initialized>> {
86        // Note: init() doesn't validate prerequisites since it's the entry point
87        // The phase execution (in exec.rs) will record the phase run
88
89        Ok(LifecycleStateMachine {
90            state: self.state,
91            _marker: PhantomData,
92        })
93    }
94}
95
96impl LifecycleStateMachine<Initialized> {
97    /// Transition from Initialized to Setup (run `setup` phase)
98    ///
99    /// **Poka-yoke**: Can only be called on `Initialized` state - compiler enforces this.
100    pub fn setup(self) -> Result<LifecycleStateMachine<Setup>> {
101        // Validate that init has been run
102        if !self.state.has_completed_phase("init") {
103            return Err(LifecycleError::Other(
104                "Cannot run setup: init phase not completed".into(),
105            ));
106        }
107
108        Ok(LifecycleStateMachine {
109            state: self.state,
110            _marker: PhantomData,
111        })
112    }
113}
114
115impl LifecycleStateMachine<Setup> {
116    /// Transition from Setup to Built (run `build` phase)
117    ///
118    /// **Poka-yoke**: Can only be called on `Setup` state - compiler enforces this.
119    pub fn build(self) -> Result<LifecycleStateMachine<Built>> {
120        // Validate that setup has been run
121        if !self.state.has_completed_phase("setup") {
122            return Err(LifecycleError::Other(
123                "Cannot run build: setup phase not completed".into(),
124            ));
125        }
126
127        Ok(LifecycleStateMachine {
128            state: self.state,
129            _marker: PhantomData,
130        })
131    }
132}
133
134impl LifecycleStateMachine<Built> {
135    /// Transition from Built to Tested (run `test` phase)
136    ///
137    /// **Poka-yoke**: Can only be called on `Built` state - compiler enforces this.
138    pub fn test(self) -> Result<LifecycleStateMachine<Tested>> {
139        // Validate that build has been run
140        if !self.state.has_completed_phase("build") {
141            return Err(LifecycleError::Other(
142                "Cannot run test: build phase not completed".into(),
143            ));
144        }
145
146        Ok(LifecycleStateMachine {
147            state: self.state,
148            _marker: PhantomData,
149        })
150    }
151}
152
153impl LifecycleStateMachine<Tested> {
154    /// Transition from Tested to Deployed (run `deploy` phase)
155    ///
156    /// **Poka-yoke**: Can only be called on `Tested` state - compiler enforces this.
157    pub fn deploy(self) -> Result<LifecycleStateMachine<Deployed>> {
158        // Validate that test has been run
159        if !self.state.has_completed_phase("test") {
160            return Err(LifecycleError::Other(
161                "Cannot run deploy: test phase not completed".into(),
162            ));
163        }
164
165        Ok(LifecycleStateMachine {
166            state: self.state,
167            _marker: PhantomData,
168        })
169    }
170}
171
172// Common implementations for all states
173
174impl<State> LifecycleStateMachine<State> {
175    /// Get the underlying lifecycle state
176    ///
177    /// This allows accessing state information regardless of the current state marker.
178    pub fn state(&self) -> &LifecycleState {
179        &self.state
180    }
181
182    /// Get mutable access to the underlying lifecycle state
183    ///
184    /// **Warning**: Modifying state directly can break type-level invariants.
185    /// Prefer using transition methods when possible.
186    pub fn state_mut(&mut self) -> &mut LifecycleState {
187        &mut self.state
188    }
189
190    /// Check if a phase has been completed
191    pub fn has_completed_phase(&self, phase: &str) -> bool {
192        self.state.phase_history.iter().any(|r| r.phase == phase)
193    }
194
195    /// Get the last completed phase
196    pub fn last_phase(&self) -> Option<&str> {
197        self.state.last_phase.as_deref()
198    }
199}
200
201impl Default for LifecycleStateMachine<Initial> {
202    fn default() -> Self {
203        Self::new()
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    #[test]
212    fn test_valid_state_transitions() {
213        // State machine validates transitions but doesn't record phases
214        // Phases are recorded in exec.rs during actual execution
215        let mut lifecycle = LifecycleStateMachine::<Initial>::new();
216        lifecycle
217            .state_mut()
218            .record_run("init".to_string(), 0, 100, true);
219        let lifecycle = lifecycle.init().unwrap();
220
221        let mut lifecycle = LifecycleStateMachine::<Initialized> {
222            state: lifecycle.state().clone(),
223            _marker: PhantomData,
224        };
225        lifecycle
226            .state_mut()
227            .record_run("setup".to_string(), 100, 200, true);
228        let lifecycle = lifecycle.setup().unwrap();
229
230        let mut lifecycle = LifecycleStateMachine::<Setup> {
231            state: lifecycle.state().clone(),
232            _marker: PhantomData,
233        };
234        lifecycle
235            .state_mut()
236            .record_run("build".to_string(), 200, 300, true);
237        let lifecycle = lifecycle.build().unwrap();
238
239        let mut lifecycle = LifecycleStateMachine::<Built> {
240            state: lifecycle.state().clone(),
241            _marker: PhantomData,
242        };
243        lifecycle
244            .state_mut()
245            .record_run("test".to_string(), 300, 400, true);
246        let lifecycle = lifecycle.test().unwrap();
247
248        let mut lifecycle = LifecycleStateMachine::<Tested> {
249            state: lifecycle.state().clone(),
250            _marker: PhantomData,
251        };
252        lifecycle
253            .state_mut()
254            .record_run("deploy".to_string(), 400, 500, true);
255        let lifecycle = lifecycle.deploy().unwrap();
256
257        assert!(lifecycle.has_completed_phase("init"));
258        assert!(lifecycle.has_completed_phase("setup"));
259        assert!(lifecycle.has_completed_phase("build"));
260        assert!(lifecycle.has_completed_phase("test"));
261        assert!(lifecycle.has_completed_phase("deploy"));
262    }
263
264    #[test]
265    fn test_state_access() {
266        let lifecycle = LifecycleStateMachine::<Initial>::new();
267        assert_eq!(lifecycle.last_phase(), None);
268        assert!(!lifecycle.has_completed_phase("init"));
269    }
270
271    #[test]
272    fn test_invalid_transition_validation() {
273        let lifecycle = LifecycleStateMachine::<Initial>::new();
274        // Cannot call setup() on Initial state - compile error!
275        // let lifecycle = lifecycle.setup().unwrap(); // This would fail to compile
276
277        // But we can transition through init first (after recording the phase)
278        let mut lifecycle = lifecycle;
279        lifecycle
280            .state_mut()
281            .record_run("init".to_string(), 0, 100, true);
282        let lifecycle = lifecycle.init().unwrap();
283        let lifecycle = LifecycleStateMachine::<Initialized> {
284            state: lifecycle.state().clone(),
285            _marker: PhantomData,
286        };
287        let _lifecycle = lifecycle.setup().unwrap(); // Now this works
288    }
289}